/*
 * 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://www.pinpointlocal.com/html';
	var assetsBaseUrl = 'http://www.pinpointlocal.com/html';
	
    var imageBaseUrl = assetsBaseUrl + '/images';
    
    // test for a badge (an always expanded button)
    var isBadge = (
        PINPOINTButton.style == 'thin-badge' || 
        PINPOINTButton.style == 'medium-badge' || 
        PINPOINTButton.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('.pinpoint-button');
    
        // get a reference to the button image and its default src
        var button = $('.pinpoint-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(PINPOINTButton.fileId==5)
		{
				var posi_abs = 'style="position:absolute;width:248px;border: 1px solid #929292 !important;"';
				PINPOINTButton.style='medium-badge';

		}
		else
		{
			var posi_abs = 'style="position:absolute;width:148px;border: 1px solid #929292 !important;"';
			PINPOINTButton.style='thin-badge';

		}
		
        var add_floating_div = function() {
            var floatingDiv = $('<div class="floating ' + PINPOINTButton.style + '" ' + posi_abs +'></div>');
            var head = $('<span class="head" style="background: none repeat scroll 0 0 #EEEEEE !important;border-bottom: 1px solid #929292 !important;color: #000000 !important;display: block !important;font-size: 11px !important;padding: 5px !important;">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" style="border-bottom: medium none;border-top: 1px solid #929292;font-size: 10px !important;background: none repeat scroll 0 0 #EEEEEE !important;color: #000000 !important;display: block !important;padding: 5px !important;">Local SEO Tools Brought To You By <a href="http://www.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(PINPOINTButton.fileId==2 || PINPOINTButton.fileId==5 || PINPOINTButton.fileId==7)
			{
				 floatingDiv.hide(); 
			}
			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(PINPOINTButton.fileId==2 || PINPOINTButton.fileId==5 || PINPOINTButton.fileId==7)
			{
				isBadge = true;
			}
			else
			{
				isBadge = true; 
			}
			  
            if (isBadge) 
			{ 
                if (typeof PINPOINTButton.interactType != 'undefined' && PINPOINTButton.interactType == 'click') 
				{
                    $('.pinpoint-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('.pinpoint-button').length === 0 && expanded) 
						{
                            floatingDiv.slideUp('fast', function() 
							{
                                revert_button();
                                expanded = false;
                            });
                        }
                    });
                } 
				else 
				{
                    var timer = false;
                    
                    $('.pinpoint-button').mouseenter(function(event) 
					{
                        clearTimeout(timer);
                        
                        update_button();
                        floatingDiv.slideDown();
                        expanded = true;
                    });
                    
                    $('.pinpoint-button').mouseleave(function(event) 
					{
                        timer = setTimeout(function() {
                            floatingDiv.slideUp('fast', function() {
                                revert_button();
                                expanded = false;
                            });
                        }, 500);
                    });
                    
                     $('.pinpoint-button .button').click(function(event) {
                        		 event.preventDefault();
                    });
                }
            } 
			else 
			{
                $('.pinpoint-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
            $('.pinpoint-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=' + PINPOINTButton.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 (PINPOINTButton.buttonId !== undefined) {
				
                jsonp_url = baseUrl + '/jsondata.php?id=' + PINPOINTButton.buttonId + '&callback=?';
				
				
            } 
			
            $.getJSON(jsonp_url, function(data) 
			{
                var li;
                
                if (data.errorMsg === undefined) {
			
                    PINPOINTButton.buttonId = data.buttonId;
                    
                    var localDiv = $('<div class="local"><ul class="classulforlocal" style="background: none repeat scroll 0 0 #FFFFFF !important;color: #474747;font-size: 11px;overflow: hidden !important;padding: 5px !important;"></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(PINPOINTButton.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>"');
                    
                    $('.pinpoint-button .loading').replaceWith(localDiv);
                  
                    
                    var uls = [], count = 0, arrayCount = -1;  					
					
					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 = '';
					
					
					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;float: left !important;list-style: none outside none !important;margin: 3px 0 !important;padding: 0 0 5px !important;'><a target='_blank'  style='' href=' "+ Reurl + "'  style='border: 1px solid #FFFFFF !important; color: #474747;display: block;font-size: 11px;padding: 5px;text-decoration: none !important;'><img src='"+ imagetoshow +"' alt='' border='0' align='absmiddle' style='padding-right:10px;'>" + nametoshow + "</a></li>";
						
						
						floatingDiv.find('.classulforlocal').append(lis);						
					}
					
                } 
            });
        };
    
        // update the graphic displayed for the button
        var update_button = function() 
		{           
		 
		   if (PINPOINTButton.style == 'thin-badge') 
		   {
                button.attr('src', imageBaseUrl + '/butt1.png');
           }
    
           if (PINPOINTButton.style == 'medium-badge') 
		   {
				
					if(PINPOINTButton.fileId==3)
					{
                		button.attr('src', imageBaseUrl + '/butt3.png');
					}
					else
					{	
						button.attr('src', imageBaseUrl + '/butt4.png');
					}
            }
    
            if (PINPOINTButton.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 + "/button/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 
	{
		add_script(assetsBaseUrl + "/js/jQuery.js", jquery_loaded);
		jQuery = window.jQuery;
		
        load_button();
    }
})();
