/*global window document $ navigator */
function getposOffset(overlay, offsettype)
{
	var totaloffset = ( offsettype == "left" ) ? overlay.offsetLeft : overlay.offsetTop;
	var parentEl = overlay.offsetParent;
	while ( parentEl !== null)
	{
		totaloffset = ( offsettype == "left" ) ? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
		parentEl = parentEl.offsetParent;
	}
	return totaloffset;
}
				
var browserName = navigator.appName; 
var subobjstr = "viewcars"; 
var opt_position = "rightbottom"; 
function overlay(curobj)
{
	if (document.getElementById)
	{
		var subobj = document.getElementById(subobjstr);
			subobj.style.display = ( subobj.style.display != "block" ) ? "block" : "none";
		var xpos = getposOffset(curobj, "left") + ( (typeof opt_position != "undefined" && opt_position.indexOf("right") != -1) ? -(subobj.offsetWidth - curobj.offsetWidth) : 0 ); 
		var ypos = getposOffset(curobj, "top") + ( (typeof opt_position != "undefined" && opt_position.indexOf("bottom") != -1) ? curobj.offsetHeight : 0 );
		if(browserName == "Netscape")
		{
			subobj.style.left = xpos - 5 + "px";
			subobj.style.top = ypos - 32 + "px";
		}
		else
		{
			subobj.style.left = xpos - 299 + "px";
			subobj.style.top = ypos - 68 + "px";
		}
		return false;
	}
	else
	{
		return true;
	}
}
				
function overlayclose()
{
	var subobj = 'viewcars'; 
	document.getElementById(subobj).style.display = "none";
}

/*------------------------------------------------------------------
 * the scrolling text function
 *----------------------------------------------------------------*/
jQuery.fn.liScroll = function(settings) {
		settings = jQuery.extend({
		travelocity: 0.07
		}, settings);		
		return this.each(function(){
				var $strip = jQuery(this);
				$strip.addClass("dealerticker");
				var stripWidth = 0;
				var $mask = $strip.wrap("<div class='mask'></div>");
				var $eventcontainer = $strip.parent().wrap("<div class='eventcontainer'></div>");								
				var containerWidth = $strip.parent().parent().width();	
				$strip.find("li").each(function(i){
				stripWidth += jQuery(this, i).width();
				});
				$strip.width(stripWidth);			
				var defTiming = stripWidth/settings.travelocity;
				var totalTravel = stripWidth+containerWidth;								
				function scrollnews(spazio, tempo){
				$strip.animate({left: '-='+ spazio}, tempo, "linear", function(){$strip.css("left", containerWidth); scrollnews(totalTravel, defTiming);});
				}
				scrollnews(totalTravel, defTiming);				
				$strip.hover(function(){
				jQuery(this).stop();
				},
				function(){
				var offset = jQuery(this).offset();
				var residualSpace = offset.left + stripWidth;
				var residualTime = residualSpace/settings.travelocity;
				scrollnews(residualSpace, residualTime);
				});			
		});	
};

function formatPrice(nStr)
{       
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;    while (rgx.test(x1))
    {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function featuredCars_callback(jsonData)
{
    if ( jsonData.featuredDealer.length > 0 )
    {
        var FD = jsonData.featuredDealer;
        var FV = jsonData.featuredVehicle;
        var VP = jsonData.vehiclePhoto;
        var SE = jsonData.salesEvent;

        // insert stylesheet into the head
        $('head').append('<link rel="stylesheet" href="http://widgets.fccinteractive.com/carshq/css/featuredCarsHQ.css" type="text/css" media="screen" />');

        var featuredVehicleList,featuredTop,randomDealer,badge,vehicle_ID,make,model,year,price,sale_price;
        /*-----------------------------------------------------
         * random choose one dealer from the list of dealers
         * ---------------------------------------------------*/

        randomDealer = Math.floor( Math.random() * FD.length );
        var dealer_ID = FD[randomDealer].dealer_ID;
        var business_name = FD[randomDealer].business_name;
        if ( FD[randomDealer].badge )
        {
            badge = FD[randomDealer].badge;
        }
        else
        {
            badge = '';
        }
        var type = FD[randomDealer].type;
        var city = FD[randomDealer].city;
        var state = FD[randomDealer].state;
        var zipCode = FD[randomDealer].zipCode;
        var phone = FD[randomDealer].phone;

        var featuredHead = $("<div></div>").attr("id", "featuredCarsHQHead");
            var headLink = $("<a></a>")
                    .attr({
                        href: "http://www.carshq.com/",
                        target: "_blank"
                    })
                    .html('<img src="http://www.carshq.com/gfx/topVehicle_head.gif" title="carsHQ: Home Page" />');
            var headH3 = $("<h3></h3>").html('<a href="http://www.carshq.com/search/index.cfm?page=search_results&top=1&amp;zip=' + zipCode + '&amp;radius=50" target="_blank" title="carsHQ: View all Top Vehicles"><span class="red">Top</span>Vehicles</a>');
            $(featuredHead).append(headLink);
            $(featuredHead).append(headH3);
        $('#featuredCars_widget').append(featuredHead);

        /*------------------------------------------------------------
         * need to count how many vehicles this dealer has and pick 
         * random one
         * ----------------------------------------------------------*/
        if ( FV.length > 0 )
        {
            var featuredVehicleCount = 0;
                featuredVehicleList = [];
            for ( var i = 0; i < FV.length; i++ )
            {
                if ( FV[i].dealer_ID == dealer_ID )
                {
                    featuredVehicleList[featuredVehicleCount] = i;
                    featuredVehicleCount += 1;
                } 
            }
            var randomNumber = Math.floor(Math.random() * featuredVehicleList.length);
            var randomVehicle = featuredVehicleList[randomNumber];

            vehicle_ID = FV[randomVehicle].vehicle_ID;
            year = FV[randomVehicle].year;
            make = FV[randomVehicle].make;
            model = FV[randomVehicle].model;
            price = FV[randomVehicle].price;
            sale_price = FV[randomVehicle].sale_price;

            var featuredBadge;
            if ( type == 'dealership')
            {
                if ( badge != '' )
                {
                    featuredTop = $("<div></div>").attr("id", "top");
                        featuredBadge = $("<span></span>").addClass("badge");
                            var badgeContent = $("<a></a>")
                                        .attr({
                                            href: "http://www.carshq.com/search/index.cfm?page=search_results&dealer_id=" + dealer_ID + "&zip=" + zipCode + "&radius=50&tab=1",
                                            target: "_blank"
                                        })
                                        .html('<img src="http://www.carshq.com/gfx/badges/' + badge + '" class="dealerLogo" title="' + business_name + '" height="35px" />');
                        $(featuredBadge).append(badgeContent);
                    $(featuredTop).append(featuredBadge);
	        }
	        else
	        {
                featuredTop = $("<div></div>").attr("id", "top");
                        featuredBadge = $("<span></span>")
                                .addClass("badge")
                                .html('<a href="http://www.carshq.com/search/index.cfm?page=search_results&dealer_id=' + dealer_ID + '&zip=' + zipCode + '&radius=50" target="_blank">' + business_name + '</a>');
                    $(featuredTop).append(featuredBadge);
                }   
                if ( featuredVehicleCount > 1 )
                {
                    var peel = $("<span></span>").addClass("peel");
                        var peelLink = $("<a></a>")
                                    .click( function() { 
                                                overlay(this);
                                            })
                                    .html('<img src="http://www.carshq.com/gfx/newpeel.gif" title="More Top Vehicles for Dealer" />');
                        $(peel).append(peelLink);
                    $(featuredTop).append(peel);
                }  
            }
            else
            {
                featuredTop = $("<div></div>").attr("id", "top");
                    featuredBadge = $("<div></div>").addClass("badge");
                        var PP_phone = $("<span></span>").addClass("privatePartyBlack").text("Phone: " + phone);
                        var PP_cityState = $("<span></span>").addClass("privatePartyBlack").text(city + ", " + state);
                    $(featuredBadge).append(PP_phone);
                    $(featuredBadge).append(PP_cityState);
                $(featuredTop).append(featuredBadge);
            }
        }

        $("#featuredCars_widget").append(featuredTop);
       
        /*------------------------------------------------------------
         * Display PHOTO HERE
         *----------------------------------------------------------*/
        var photoLink,vehiclePhoto;
        var photo = $("<div></div>").attr("id", "photo");
            
        if ( VP.length > 0 )
        {
            /*------------------------------------------------------------
             * loop through all the possible photos looking for vehicle_ID
             *----------------------------------------------------------*/
            for ( var k = 0; k < VP.length; k++ )
            {
                // evaluate at i
                if ( VP[k].vehicle_ID == vehicle_ID )
                {
                    vehiclePhoto = VP[k].photo;
                }
            }
            if (vehiclePhoto)
            {
                photoLink = $("<a></a>")
                        .attr({
                            href: "http://www.carshq.com/search/index.cfm?page=detail&id=" + vehicle_ID + "&dealer_id=" + dealer_ID + "&zip=" + zipCode + "&radius=50&tab=",
                            title: "View this " + make + " " + model + " at carsHQ",
                            target: "_blank"
                        })
                        .html('<img src="http://www.carshq.com/gfx/180x135/' + vehiclePhoto + '" title="View this ' + year + ' ' + make + ' ' + model + ' at carsHQ" />');
            }
        }
        else
        {
            photoLink = $("<a></a>")
                    .attr({
                        href: "http://www.carshq.com/search/index.cfm?page=detail&id=" + vehicle_ID + "&dealer_id=" + dealer_ID + "&zip=" + zipCode,
                        title: "View this " + year + " " + make + " " + model + "at carsHQ",
                        target: "_blank"
                    })
                    .html('<img src="http://www.carshq.com/gfx/180x135/no_pic.jpg" title="No Image Available" />');
        }
        $(photo).append(photoLink);
        
        /*------------------------------------------------------------
         * Display VEHICLE DETAILS HERE
         *----------------------------------------------------------*/
        var sash = $("<div></div>").attr("id", "sash");
            var topYear = $("<div></div>").addClass("topYear").text(year);
            var topMake = $("<div></div>").addClass("topMake").text(make);
            var topModel = $("<div></div>").addClass("topModel").text(model);
            var bottomSash = $("<div></div>").addClass("bottomSash");
            if ( price != '0' )
            {
                if ( sale_price != '0' )
                {
                    $(bottomSash).html('<span class="strike">$' + formatPrice(price) + '</span><br />$' +formatPrice(sale_price));
                }
                else
                {
                    $(bottomSash).text('$' + formatPrice(price));
                }
            }
            else
            {
                $(bottomSash).text("Contact for price");
            }
            $(sash).append(topYear);
            $(sash).append(topMake);
            $(sash).append(topModel);
            $(sash).append(bottomSash);

        $(photo).append(sash);
         
        var clearBoth = $("<div></div>").addClass("clearBoth");
        $(photo).append(clearBoth);                           
    $("#featuredCars_widget").append(photo);

    /*------------------------------------------------------------
     * salesEvent section starts
     *----------------------------------------------------------*/
    if ( SE.length > 0 )
    {
        /*------------------------------------------------------------
         * need to grab all sales events for dealer_ID
         *----------------------------------------------------------*/
        var salesEventLI,seName,seDescription;
        var buildUL = 0;
        var salesEventUL = $("<ul></ul>").attr("id", "featuredSalesEvent");
            for ( var j = 0; j < SE.length; j++ )
            {
                if ( SE[j].dealer_ID == dealer_ID )
                {
                    seName = SE[j].name;
                    seDescription = SE[j].description;

                    salesEventLI = $("<li></li>").html("<strong>" + seName + "</strong> " + seDescription);
                    $(salesEventUL).append(salesEventLI);
                    // declare a variable so we know to build UL
                    buildUL++;
                }
            }
        if ( buildUL > 0 )
        {
            $("#featuredCars_widget").append(salesEventUL);
        
            // trigger the scroller
            $(function(){ 
                $("ul#featuredSalesEvent").liScroll({travelocity: 0.05}); 
            });
        } 
    }
    /*------------------------------------------------------------
     * salesEvent section ends
     *----------------------------------------------------------*/

    /*------------------------------------------------------------
     * extra view cars section starts
     * DO NOT REMOVE outer most DIV tag with id="viewcars"
     *----------------------------------------------------------*/
        var viewcars = $("<div></div>").attr("id", "viewcars");
	// insert the logos here 
            var leftLogo = $("<div></div>").addClass("leftLogo");
                var leftLogoLink = $("<a></a>")
                            .attr({
                                href: "http://www.carshq.com/",
                                target: "_blank"
                            })
                            .html('<img src="http://www.carshq.com/gfx/carsHQsmall_logo.gif" border="0" title="carsHQ: Home Page" />');
            $(leftLogo).append(leftLogoLink);
            $(viewcars).append(leftLogo);
            var rightLogo = $("<div></div>").addClass("rightLogo");
                var rightLogoLink = $("<a></a>")
                            .click( function()
                            {
                                overlayclose(); 
                                return false;
                            })
                            .html('<img src="http://www.carshq.com/gfx/close.gif" border="0" title="Close Window" />');
                $(rightLogo).append(rightLogoLink);
            $(viewcars).append(rightLogo);
                clearBoth = $("<div></div>").addClass("clearBoth");
            $(viewcars).append(clearBoth);

        /*------------------------------------------------------------
         * output each vehicle in box that floats left
         * using the featuredVehicleList, we will output all the other
         * dealers vehicles minus the one that matches vehice_ID
         *----------------------------------------------------------*/
        if ( featuredVehicleList.length > 1 )
        {
            var vc_ID,vc_year,vc_make,vc_model,vc_price,vc_sale_price,carbox,final_price,vc_vehiclePhoto;
            for ( var l = 0; l < featuredVehicleList.length; l++ )
            {
                vc_ID = featuredVehicleList[l];
                var vc_vehicle_ID = FV[vc_ID].vehicle_ID;
                if ( vc_vehicle_ID != vehicle_ID )
                {
                    vc_year = FV[vc_ID].year;
                    vc_make = FV[vc_ID].make;
                    vc_model = FV[vc_ID].model;
                    vc_price = FV[vc_ID].price;
                    vc_sale_price = FV[vc_ID].sale_price;
      
                    carbox = $("<div></div>").addClass("carbox", "float");
                
                    if ( VP.length > 0 )
                    {
                        /*------------------------------------------------------------
                         * loop through all the possible photos looking for vehicle_ID
                         *----------------------------------------------------------*/
                        for ( var m = 0; m < VP.length; m++ )
                        {
                            // evaluate at m
                            if ( VP[m].vehicle_ID == vc_vehicle_ID )
                            {
                                vc_vehiclePhoto = VP[m].photo;
                            }
                         }

                         if ( vc_vehiclePhoto )
                         {
                             vc_link = $("<a></a>")
                                     .attr({
                                         href: "http://www.carshq.com/search/index.cfm?page=detail&id=" + vc_vehicle_ID + "&dealer_id=" + dealer_ID + "&zip=" + zipCode + "&radius=50&tab=1",
                                         title: "View this " + vc_year + " " + vc_make + " " + vc_model + " at carsHQ.com",
                                         target: "_blank"
                                     })
                                     .html('<img src="http://www.carshq.com/gfx/96x72/' + vc_vehiclePhoto + '" width="60" title="view this ' + vc_year + ' ' + vc_make + ' ' + vc_model + ' at carsHQ.com" />');
                             $(carbox).append(vc_link);
                         }
                         else
                         {
                             vc_link = $("<a></a>")
                                     .attr({
                                         href: "http://www.carshq.com/search/index.cfm?page=detail&id=" + vc_vehicle_ID + "&dealer_id=" + dealer_ID + "&zip=" + zipCode + "&radius=50&tab=1",
                                         title: "View this " + vc_year + " " + vc_make + " " + vc_model + " at carsHQ.com",
                                         target: "_blank"
                                     })
                                     .html('<img src="http://www.carshq.com/gfx/96x72/no_pic.jpg" width="60" title="view this ' + vc_year + ' ' + vc_make + ' ' + vc_model + ' at carsHQ.com" />');
                             $(carbox).append(vc_link);
                         }
                         $(viewcars).append(carbox);
                    }
                    if ( vc_price != '0' )
                    {
                        if ( vc_sale_price != '0' )
                        {
                            final_price = $('<span></span>').addClass('strike').text('$' + formatPrice(vc_price));
                            $(carbox).append(final_price);
                            vc_sale_price = '<br />$' + formatPrice(vc_sale_price);
                            $(carbox).append(vc_sale_price);
                        }
                        else
                        {
                            final_price= '$' + formatPrice(vc_price);
                            $(carbox).append(final_price);
                        }
                    }
                    else
                    {
                        final_price = "Contact for price";
                        $(carbox).append(final_price);
                    }
                }

            }
            
            var bottomLink;
            var bottom = $("<div></div>").attr("id", "bottom");
            if ( badge !== "" )
            {
                bottomLink = $("<a></a>")
                        .attr({
                            href: "http://www.carshq.com/search/index.cfm?page=search_results&dealer_id=" + dealer_ID + "&zip=" + zipCode + "&radius=50&tab=1",
                            target: "_blank"
                        })
                        .html('<img src="http://www.carshq.com/gfx/badges/' + badge + '" border="0" title="' +  business_name + '" />');
                $(bottom).append(bottomLink);
            }
            else
            {
                bottomLink = $("<a></a>")
                        .attr({
                            href: "http://www.carshq.com/search/index.cfm?page=search_results&dealer_id=" + dealer_ID + "&zip=" + zipCode + "&radius=50",
                            target: "_blank"
                        })
                        .text(business_name);
                $(bottom).append(bottomLink);
            }
            $(viewcars).append(bottom);
        }
    $("#featuredCars_widget").append(viewcars);
    /*------------------------------------------------------------
     * extra view cars section ends
     *----------------------------------------------------------*/
    }
}