/*
 * ReviewBiz Button
 * Copyright 2010 BrightLocal.com
 * Written by Ed Eliot
 */
 
(function() {
    // holds reference to jquery object
    var jQuery;
    
    // base URL for requesting assets etc
    // a relative path can't be used due to the reverse proxying being used
    var baseUrl = 'http://www.brightlocal.com';
    var assetsBaseUrl = 'http://static.brightlocal.com/review-biz';
    var imageBaseUrl = assetsBaseUrl + '/images/buttons/' + REVIEW_BIZ.country.toLowerCase();
    
    // test for a badge (an always expanded button)
    var isBadge = (
        REVIEW_BIZ.style == 'thin-badge' || 
        REVIEW_BIZ.style == 'medium-badge' || 
        REVIEW_BIZ.style == 'wide-badge'
    );

    // main code for widget is located in this object
    var main = function($) {
        // get the parent for this script - should be the div containing the widget
        var container = $(currentScript).parent('.review-biz-button');
    
        // get a reference to the button image and its default src
        var button = $('.review-biz-button .button img');
        var buttonDefault = button.attr('src');
    
        // set a flag for storing whether or not the widget is expanded or collapsed
        var expanded = false;
    
        // dynamically add a CSS file to the page
        var add_css = function(css) { 
            var css_link = $("<link>", { 
                rel: "stylesheet", 
                type: "text/css", 
                href: css 
            });
            css_link.appendTo('head');
        };
    
        // add the widget's floating layer
        var add_floating_div = function() {
            var floatingDiv = $('<div class="floating ' + REVIEW_BIZ.style + '"></div>');
            var head = $('<span class="head">Please leave a positive review about this business on your favourite search engine, directory or social media website. Thanks!</span>');
            var foot = $('<span class="foot">Local SEO tools brought to you by <a href="http://www.brightlocal.com/">BrightLocal.com</a></span>');
            var loading = $('<div class="loading">Loading local directory links. Please wait...</div>');
    
            floatingDiv.append(head).append(loading).append(foot);
        
            // only hide the layer if it isn't a badge
            if (!isBadge) {
                floatingDiv.hide();
            }
        
            container.append(floatingDiv);
            floatingDiv.css({
                'top' : container.position().top + button.attr('height') + 'px',
                'left' : container.position().left + 'px'
            });
        
            return floatingDiv;
        };
    
        // add events to allow opening and closing of floating layer
        var add_events = function() {
            // click events don't need to be added for a badge as it doesn't expand and collapse
            if (!isBadge) {
                if (typeof REVIEW_BIZ.interactType != 'undefined' && REVIEW_BIZ.interactType == 'click') {
                    $('.review-biz-button .button').click(function(event) {
                        if (expanded) {
                            floatingDiv.slideUp('fast', function() {
                                revert_button();
                                expanded = false;
                            });
                        } else {
                            update_button();
                            floatingDiv.slideDown();
                            expanded = true;
                        }
                        event.preventDefault();
                    });
                    
                    // hide the expanded part if clicking anywhere outside the widget
                    $('body').click(function(event) {
                        if ($(event.target).parents('.review-biz-button').length === 0 && expanded) {
                            floatingDiv.slideUp('fast', function() {
                                revert_button();
                                expanded = false;
                            });
                        }
                    });
                } else {
                    var timer = false;
                    
                    $('.review-biz-button').mouseenter(function(event) {
                        clearTimeout(timer);
                        
                        update_button();
                        floatingDiv.slideDown();
                        expanded = true;
                    });
                    
                    $('.review-biz-button').mouseleave(function(event) {
                        timer = setTimeout(function() {
                            floatingDiv.slideUp('fast', function() {
                                revert_button();
                                expanded = false;
                            });
                        }, 500);
                    });
                    
                     $('.review-biz-button .button').click(function(event) {
                        event.preventDefault();
                    });
                }
            } else {
                $('.review-biz-button .button').click(function(event) {
                    event.preventDefault();
                });
            }
        
            // add events to capture clicks for tracking
            // a live event handler needs to be added here as 
            // the links they refer to are added dynamically
            $('.review-biz-button li a').live('click', function(event) {
                var a = $(event.target);
            
                if (a.attr('href').indexOf('www.brightlocal.com') === -1) {
                    a.attr('href', baseUrl + '/redirect/?id=' + REVIEW_BIZ.buttonId + '&url=' + escape(a.attr('href')));
                    document.location.href = a.attr('href');
                    event.preventDefault();
                }
            });
        };
    
        // get link data for widget
        var get_data = function() {
            var jsonp_url;
            
            // check to see if we're creating a static or dynamic widget
            if (REVIEW_BIZ.buttonId !== undefined) {
                jsonp_url = baseUrl + '/api/v1/get-static-button-urls/?id=' + REVIEW_BIZ.buttonId + '&callback=?';
            } else {
                jsonp_url = baseUrl + '/api/v1/get-dynamic-button-urls/?';
                jsonp_url += 'contact=' + REVIEW_BIZ.contactId;
                jsonp_url += '&style=' + REVIEW_BIZ.style;
                jsonp_url += '&q=' + escape(REVIEW_BIZ.q);
                jsonp_url += '&location=' + escape(REVIEW_BIZ.location);
                jsonp_url += '&category=' + REVIEW_BIZ.category;
                jsonp_url += '&country=' + REVIEW_BIZ.country;
                jsonp_url += '&callback=?';
            }

            $.getJSON(jsonp_url, function(data) {
                var li;
                
                if (data.errorMsg === undefined) {
                    REVIEW_BIZ.buttonId = data.buttonId;
                    
                    var localDiv = $('<div class="local"></div>');
                    var socialNetworksDiv = $('<ul class="social"></ul>');
                    var facebook = $(
                        '<li><a href="http://www.facebook.com/share.php?u=' + escape(document.location.href) + '" class="facebook">Facebook</a></li>'
                    );
                    var twitter = $(
                        '<li><a href="http://twitter.com/share?url=' + escape(document.location.href) + '&text=' + escape(REVIEW_BIZ.businessName) + escape(' is a great local business, I really recommend that you try them out - ') + '&via=bright_local' +
                        '" class="twitter">Twitter</a></li>"'
                    );
                    
                    $('.review-biz-button .loading').replaceWith(localDiv);
                    localDiv.after(socialNetworksDiv);
                    socialNetworksDiv.append(facebook).append(twitter);
                    
                    var uls = [], count = 0, arrayCount = -1;
                    
                    for (var i in data.results) {
                        if (data.results[i].url !== '') {
                            li = $('<li><a></a></li>').find('a').attr({
                                'href' : data.results[i].url,
                                'class' : i
                            }).html(data.results[i].name).end();
                            
                            if ((count === 0) || (
                                (count % 2) == 0 && (
                                    REVIEW_BIZ.style !== 'thin-double-button' && 
                                    REVIEW_BIZ.style !== 'thin-badge')
                                )
                            ) {
                                arrayCount++;
                                uls[arrayCount] = $('<ul></ul>');
                            }
                            
                            uls[arrayCount].append(li);
                            
                            count++;
                        }
                    }
                    
                    for (var i in uls) {
                        floatingDiv.find('.local').append(uls[i]);
                    }
                } else {
                    // TODO: put this in a paragraph instead of as a list item
                    li = $('<li>' + data.errorMsg + '</li>');
                    floatingDiv.find('.local').append(li);
                }
            });
        };
    
        // update the graphic displayed for the button
        var update_button = function() {
            if (REVIEW_BIZ.style == 'thin-double-button' || REVIEW_BIZ.style == 'thin-badge') {
                button.attr('src', imageBaseUrl + '/thin-double-top.png');
            }
    
            if (REVIEW_BIZ.style == 'medium-single-button' || REVIEW_BIZ.style == 'medium-badge') {
                button.attr('src', imageBaseUrl + '/medium-single-top.png');
            }
    
            if (REVIEW_BIZ.style == 'medium-double-button') {
                button.attr('src', imageBaseUrl + '/medium-double-top.png');
            }
    
            if (REVIEW_BIZ.style == 'wide-single-button' || REVIEW_BIZ.style == 'wide-badge') {
                button.attr('src', imageBaseUrl + '/wide-single-top.png');
            }
        };
        
        var revert_button = function() {
            button.attr('src', buttonDefault);
        };
    
        // preload images for widget expanded state to prevent a delay when the user 
        // clicks on a button
        var preload_images = function() {
            var thinDoubleTop = new Image();
            var mediumSingleTop = new Image();
            var mediumDoubleTop = new Image();
            var wideSingleTop = new Image();
            thinDoubleTop.src = imageBaseUrl + '/thin-double-top.png';
            mediumSingleTop.src = imageBaseUrl + '/medium-single-top.png';
            mediumDoubleTop.src = imageBaseUrl + '/medium-double-top.png';
            wideSingleTop.src = imageBaseUrl + '/wide-single-top.png';
        };
    
        // call methods to set up
        add_css(assetsBaseUrl + "/css/review-biz.css");
        var floatingDiv = add_floating_div();
    
        // update the button image straight away if it's a badge
        // the expanded layer is shown as soon as the JavaScript is loaded
        if (isBadge) {
            update_button();
        }
    
        // add events to hide and show the expanded part of the widget
        add_events();
        // get link data for the widget
        get_data();
        // preload button images
        preload_images();
    };
    
    var load_button = function() {
        // if it's a badge we can load the panel straight away
        // if it's a button we need to wait until the page has finished 
        // loading because other JavaScript code could rewrite the page 
        // changing the position of the button
        if (isBadge) {
            main(jQuery);
        } else {
            jQuery(window).load(function() {
               main(jQuery); 
            });
        }
    };
    
    // called once jquery library has been loaded
    var jquery_loaded = function() {
        jQuery = window.jQuery.noConflict(true);
        load_button();
    };

    // dynamically add a script node to the page
    var add_script = function(src, callback) {
        var script = document.createElement('script');
        script.setAttribute("type","text/javascript");
        script.setAttribute("src", src);
        script.onload = callback;
        script.onreadystatechange = function () {
            if (this.readyState == 'complete' || this.readyState == 'loaded') {
                callback();
            }
        };
        document.getElementsByTagName("head")[0].appendChild(script);
    };
    
    var current_script = function() {
        var scripts = document.getElementsByTagName('script');
        return scripts[scripts.length - 1];
    };

    // store reference to script node that called this script for use elsewhere
    var currentScript = current_script();

    // check if jquery is already in use on the page
    if ((window.jQuery === undefined) || (/1\.(0|1|2|3)\.*/).test(window.jQuery.fn.jquery)) {
        add_script(assetsBaseUrl + "/js/jquery.js", jquery_loaded);
    } else {
        jQuery = window.jQuery;
        load_button();
    }
})();
