/*
 * 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://localhost/DigitalRain';
    //var assetsBaseUrl = 'http://localhost/DigitalRain';
	var baseUrl = 'http://digitalrain.biz';
	var assetsBaseUrl = 'http://digitalrain.biz';
	
    var imageBaseUrl = assetsBaseUrl + '/images';
    
    // test for a badge (an always expanded button)
    var isBadge = (
        DIGITALRAIN.style == 'thin-badge' || 
        DIGITALRAIN.style == 'medium-badge' || 
        DIGITALRAIN.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('.digitalrain-button');
    
        // get a reference to the button image and its default src
        var button = $('.digitalrain-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
		
		if(DIGITALRAIN.fileId==2 || DIGITALRAIN.fileId==5 || DIGITALRAIN.fileId==7)
		{
				var posi_abs = '';
		}
		else
		{
			var posi_abs = 'style="position:absolute;"';
		}
		
        var add_floating_div = function() {
            var floatingDiv = $('<div class="floating ' + DIGITALRAIN.style + '" ' + posi_abs +'></div>');
            var head = $('<span class="head">Please leave a positive review about this business on your favorite search engine, directory or social media website. Thanks!</span>');
 var foot = $('<span class="foot">Local SEO Tools Brought To You By <a href="http://pinpointlocal.com">PinPoint Local</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();
            }
			
			if(DIGITALRAIN.fileId==2 || DIGITALRAIN.fileId==5 || DIGITALRAIN.fileId==7)
			{
				// do something 
			}
			else
			{ 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(DIGITALRAIN.fileId==2 || DIGITALRAIN.fileId==5 || DIGITALRAIN.fileId==7){
				isBadge = false;
			}
			else{ isBadge = true; }
			  
            if (isBadge) { 
                if (typeof DIGITALRAIN.interactType != 'undefined' && DIGITALRAIN.interactType == 'click') {
                    $('.digitalrain-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('.digitalrain-button').length === 0 && expanded) {
                            floatingDiv.slideUp('fast', function() {
                                revert_button();
                                expanded = false;
                            });
                        }
                    });
                } else {
                    var timer = false;
                    
                    $('.digitalrain-button').mouseenter(function(event) {
                        clearTimeout(timer);
                        
                        update_button();
                        floatingDiv.slideDown();
                        expanded = true;
                    });
                    
                    $('.digitalrain-button').mouseleave(function(event) {
                        timer = setTimeout(function() {
                            floatingDiv.slideUp('fast', function() {
                                revert_button();
                                expanded = false;
                            });
                        }, 500);
                    });
                    
                     $('.digitalrain-button .button').click(function(event) {
                        		 event.preventDefault();
                    });
                }
            } else {
                $('.digitalrain-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
            $('.digitalrain-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=' + DIGITALRAIN.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 (DIGITALRAIN.buttonId !== undefined) {
                jsonp_url = baseUrl + '/jsondata.php?id=' + DIGITALRAIN.buttonId + '&callback=?';
            } else {
                /*jsonp_url = baseUrl + '/api/v1/get-dynamic-button-urls/?';
                jsonp_url += 'contact=' + DIGITALRAIN.contactId;
                jsonp_url += '&style=' + DIGITALRAIN.style;
                jsonp_url += '&q=' + escape(DIGITALRAIN.q);
                jsonp_url += '&location=' + escape(DIGITALRAIN.location);
                jsonp_url += '&category=' + DIGITALRAIN.category;
                jsonp_url += '&country=' + DIGITALRAIN.country;
                jsonp_url += '&callback=?';*/
            }
			
            $.getJSON(jsonp_url, function(data) {
                var li;
                
                if (data.errorMsg === undefined) {
                    DIGITALRAIN.buttonId = data.buttonId;
                    
                    var localDiv = $('<div class="local"><ul class="classulforlocal"></ul></div>');
                    var socialNetworksDiv = $('<ul class="social"></ul>');
                    var facebook = $('<li><a href="http://www.facebook.com/share.php?u=' + escape(document.location.href) + '" class=""><img src="' + baseUrl + '/images/icn_facebook.gif" border="0"/>Facebook</a></li>'
                    );
                    var twitter = $('<li><a href="http://twitter.com/share?url=' + escape(document.location.href) + '&text=' + escape(DIGITALRAIN.businessName) + escape(' is a great local business, I really recommend that you try them out - ') + '&via=bright_local' +'" class=""><img src="' + baseUrl + '/images/icn_twitter.gif" border="0"/>Twitter</a></li>"');
                    
                    $('.digitalrain-button .loading').replaceWith(localDiv);
                  // localDiv.after(socialNetworksDiv);
                  //  socialNetworksDiv.append(facebook).append(twitter);
                    
                    var uls = [], count = 0, arrayCount = -1;  					
					//alert(data.middledata);					
					//floatingDiv.find('.classulforlocal').append(data.middledata);
					
					var newda = data.middledata;					
					//floatingDiv.find('.classulforlocal').append(newda);
					
					var msg   = newda.split("@!");
					
					var totallen = msg.length;
					var indata = '';
					var nametoshow = '';
					var Reurl = ''; 
					var imagetoshow = ''; 
					var lis = '';
					
					//lis = '<ul>';
					
					var k=1;
					for(var i=0;i<msg.length;i++)
					{	
						indata = msg[i].split("|||");												
						nametoshow = indata[0];
						Reurl = indata[1]; 
						imagetoshow = imageBaseUrl+"/"+indata[2];							
						
						lis = "<li style='height:25px;'><a target='_blank'  style='' href=' "+ Reurl + "' ><img src='"+ imagetoshow +"' alt='' border='0' align='absmiddle'>" + nametoshow + "</a></li>";
						
						/*if(k==4)
						{
							lis += '</ul><ul>';
							k=1;
						}
						else
						{
							k++;
						}*/
						
						floatingDiv.find('.classulforlocal').append(lis);						
					}
						
					//lis += '</ul>';					
					
                    /*	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 && (
                                    DIGITALRAIN.style !== 'thin-double-button' && 
                                    DIGITALRAIN.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 (DIGITALRAIN.style == 'thin-badge') {
                button.attr('src', imageBaseUrl + '/butt1.png');
            }
    
            if (DIGITALRAIN.style == 'medium-badge') {
				
					if(DIGITALRAIN.fileId==3)
					{
                		button.attr('src', imageBaseUrl + '/butt3.png');
					}
					else
					{	
						button.attr('src', imageBaseUrl + '/butt4.png');
					}
            }
    
            if (DIGITALRAIN.style == 'wide-badge') {
                button.attr('src', imageBaseUrl + '/butt6.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 + '/butt1.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/digitalrain_but.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();
    }
})();
