var thisURL = location.toString();
var thisLang = "en";
var thisLangLong = "english";
var vehicleMake = "";
var akamai_vdo = false;

if ((thisURL.indexOf('/french') != -1)|| (thisURL.indexOf('fr_CA') != -1)) {
	thisLang = "fr";
	thisLangLong = "french";
}
jQuery(document).ready(function () {
    if (thisURL.indexOf('/dealer-view') != -1) {
        if (thisURL.indexOf('pagetype=i') != -1) {
            $("a").each(function () {
                var thisHref = $(this).attr("href");
                if (thisHref) {
                    if (thisHref.indexOf("pagetype") == -1 && thisHref.indexOf("javascript") == -1 && thisHref.substr(0, 1) != "#") { // exclusions
                        var newHref = thisHref.indexOf("?") == -1 ? thisHref + "?pagetype=i" : thisHref + "&pagetype=i"
                        $(this).attr("href", newHref);
                    }
                }
            });
            $("form").append("<input type=\"hidden\" name=\"pagetype\" value=\"i\" />");
        }
        if ($("a.aceLink").length > 0) {
            $("a.aceLink").attr("target", "_blank");
        }
    }
	
    if ($('#galleryCarousel').length > 0) {
        $('#galleryCarousel').css("visibility", "hidden");
        jQuery('#galleryCarousel').jcarousel({
            initCallback: galleryCarousel_initCallback,
            itemLoadCallback: galleryCarousel_itemLoadCallback,
            scroll: 9
        });

        $('#galleryCarousel a').click(function (e) {
            e.preventDefault();
            if ($('#galleryCarousel li').length == 1) {
                return;
            }
            // 2009/08/28 -- MC changes to accommodate .gif thumbnails
            //large_image_src = e.target.src.replace(/(\d+).jpg/, 'big_$1.jpg');
            large_image_src = e.target.src.replace('.gif', '.jpg');
            large_image_src = large_image_src.replace(/(\d+).jpg/, 'big_$1.jpg');

			changeBigImage(large_image_src);
			
            toggleActiveCarouselItem('', "clearAll");
			
			if(akamai_vdo==true){
				var akamaivdopath=$(this).parent("li").attr("alt");
				toggleActiveCarouselItem(akamaivdopath, "on", true);
			}else{
				toggleActiveCarouselItem($(e.target).parent().parent(), "on");
			}
			
        });

        //$('#galleryCarousel a img').hover(
        //	function() {
        //		swapCarouselImage(this)
        //	},
        //	function() {
        //		swapCarouselImage(this);
        //	}
        //);
	
        $('#galleryCarousel a img[src*=_off]').parent().css({ 'border-color': 'white' }); // override CSS border for carousel images with on/off state
        $('#photoNext').html('<a href="#"></a>');
        $('#photoPrev').html('<a href="#" class="disabled"></a>');
		
        if ($('#galleryCarousel li').length == 1) {
            $('#photoNext a').addClass('disabled');
        }
        var firstImage = $("#vehicle").attr("src");
		
		//For some Video Galleries the Video comes directly from AKAMAI.
		//The path for AKAMAI videos is stored in small image title tag, which is present in the #captionTitle DIV on awards page.
		var small_img_title=$('#captionTitle').html();
		
		//Check if the title has "/", which indicates a path(for AKAMAI vdo) rather than a proper title.
		if(small_img_title.indexOf("/ovp_features")!= -1){
			akamai_vdo=true;
		}
		
        if ((firstImage.indexOf('_threesixty_') != -1) || (firstImage.indexOf('_videos_') != -1)) {
			if(akamai_vdo==true){
				small_img_title=changeVideoLang(small_img_title);
				loadAkamaiVideo(small_img_title);
				
				if(thisLang=="en"){
					$("#galleryCarousel img").attr("alt","Buick Verano Video");
					$("#galleryCarousel a").attr("title","Buick Verano Video");
				}else{
					$("#galleryCarousel img").attr("alt","Video de la Buick Verano");
					$("#galleryCarousel a").attr("title","Video de la Buick Verano");
				}
			}else{
				loadFlashGallerySWF(firstImage);	
			}
        }
		
    }

    /* 
    * Animation effects for navigation on oveview pages
    */

    /**
    * @author Alexander Farkas
    * v. 1.02
    */

    (function ($) {
        $.extend($.fx.step, {
            backgroundPosition: function (fx) {
                if (fx.state === 0 && typeof fx.end == 'string') {
                    var start = $.curCSS(fx.elem, 'backgroundPosition');
                    start = toArray(start);
                    fx.start = [start[0], start[2]];
                    var end = toArray(fx.end);
                    fx.end = [end[0], end[2]];
                    fx.unit = [end[1], end[3]];
                }
                var nowPosX = [];
                nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
                nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
                fx.elem.style.backgroundPosition = nowPosX[0] + ' ' + nowPosX[1];

                function toArray(strg) {
                    strg = strg.replace(/left|top/g, '0px');
                    strg = strg.replace(/right|bottom/g, '100%');
                    strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g, "$1px$2");
                    var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
                    return [parseFloat(res[1], 10), res[2], parseFloat(res[3], 10), res[4]];
                }
            }
        });
    })(jQuery);

    if ($('#container.overview').length > 0) {
        $('div.overview #rightNav').hover(function () {
            $('a#theDesign > span').css({ backgroundPosition: "-120px -282px" });
        },
		function () {
		    $('a#theDesign > span').css({ backgroundPosition: "-120px -324px" });
		});
    }

    /*
    * END OF for navigation on oveview pages
    */

    // Augments hover state control for leftCol primary section navigation tabs
    $('#leftCol .sectionPrimaryNav ul li.activeNav ul, #leftCol .sectionPrimaryNav ul li:hover ul, #leftCol .sectionPrimaryNav ul li a:hover ul').css({ 'background': 'transparent' });
    $('#leftCol .sectionPrimaryNav > ul > li:not(.activeNav)').hover(function () {
        if ($(this).children('a').attr('id').indexOf('theDetails') != -1) {
            $('#theDesign').css({ 'background-position': '0 0' });
            $('#theDesign .navButton').addClass('navButtonOff');
        }
        else {
            $('#theDetails').css({ 'background-position': '0 -96px' });
            $('#theDetails .navButton').addClass('navButtonOff');
        }
        $('#leftCol .sectionPrimaryNav > ul > li.activeNav ul.sectionPrimaryNavList').hide();
    },
	function () {
	    if ($(this).children('a').attr('id').indexOf('theDetails') != -1) {
	        $('#theDesign').css({ 'background-position': '0 -48px' });
	        $('#theDesign .navButton').removeClass('navButtonOff');
	    }
	    else {
	        $('#theDetails').css({ 'background-position': '0 -144px' });
	        $('#theDetails .navButton').removeClass('navButtonOff');
	    }
	    $('#leftCol .sectionPrimaryNav > ul > li.activeNav ul.sectionPrimaryNavList').show();
	});

    // remove bottom border from last li child
    $('ul.sectionPrimaryNavList li:last-child').css({ 'border-bottom': 'none' });

    // if on model comparison page, equalize column height
    if ($('#modelsCompare').length > 0) {
        equalizeModelDivHeight();
    }

    // initialize accordion if necessary, implement deeplinking using query string, and add icons to right side of accordion headers, and activate showAll button
    if ($('#accordion').length > 0) {

        var params = {};
        var accordion_index, active_state;
        var anchor = decodeURI(location.href).split('#').pop();
        var accordion_count = $("#accordion").children("h5").length;

        if (thisLang == "en" && accordion_count > 1) {
            $('#accordionButtons').prepend('<a href="#" id="showAll" class="button">Show all<span></span></a>');
        }
        else if (thisLang == "fr" && accordion_count > 1) {
            $('#accordionButtons').prepend('<a href="#" id="showAll" class="button">Afficher tous<span></span></a>');
        }
        if (anchor != '') {
            $('#accordion h5 > a').each(function (i) {
                if ($(this).attr('name') == anchor)
                    accordion_index = i;
            });
            (accordion_index <= $('#accordion div').length) ? active_state = accordion_index : active_state = 0;
        }
        // browser sniffing considered harmful, but opera doesn't like long accordions with autoHeight: false
        var doAutoHeight = false;
        if (navigator.userAgent.indexOf('Opera/9') != -1 && accordion_count > 5) {
            doAutoHeight = true;
        }
        // ditto: firefox won't deeplink correctly to long accordions
        if (navigator.userAgent.indexOf('Firefox') != -1 && anchor != '') {
            var anchorOffset = $("#accordion h5 a[name$='" + anchor + "']").offset();
            window.scroll(0, anchorOffset.top);
        }
        if (accordion_count > 1) {
            $("#accordion").accordion({
                icons: { 'header': 'ui-icon-triangle-1-s', 'headerSelected': 'ui-icon-triangle-1-n' },
                autoHeight: doAutoHeight,
                collapsible: true,
                active: active_state
            }).bind('accordionchange', function (event, ui) {
                var newHeaderOffset = ui.newHeader.offset();

                if ($(ui.newHeader).attr('class')) {
                    var anchorName = $(ui.newHeader).attr('class');
                    anchorName = anchorName.split(" ");
                    window.location.hash = "#" + anchorName[0];
                    window.scroll(0, newHeaderOffset.top);
                }
                //else{
                //	window.location.hash = "#none";
                //}
            })
			.find('h5').each(function (i) {
			    if ($(this).hasClass('.ui-state-active')) {
			        $(this).append('<span class="ui-icon ui-icon-triangle-1-n" style="position: absolute; left: 640px;"></span>');
			    }
			    else
			        $(this).append('<span class="ui-icon ui-icon-triangle-1-s" style="position: absolute; left: 640px;"></span>');
			});

            $('#showAll').click(function () {
                if ($('#accordion').hasClass('ui-widget') == true) {
                    $('#accordion').accordion('destroy');
                    if (thisLang == "en") {
                        $(this).html('Hide All<span></span>');
                    }
                    else {
                        $(this).html('Cacher tous<span></span>');
                    }
                }
                else {
                    $("#accordion").accordion({
                        icons: { 'header': 'ui-icon-triangle-1-s', 'headerSelected': 'ui-icon-triangle-1-n' },
                        autoHeight: false,
                        collapsible: true,
                        active: false
                    }).find('h5').append('<span class="ui-icon ui-icon-triangle-1-s" style="position: absolute; left: 640px;"></span>');

                    if (thisLang == "en") {
                        $(this).html('Show All<span></span>');
                    }
                    else {
                        $(this).html('Afficher tous<span></span>');
                    }
                }
                return false;
            });
            $('#subModelsAnchors li a, #optionsSpecsAnchors li a').each(function (i) {
                $(this).bind('click', function () {
                    if ($('#accordion h5:eq(' + i + ')').hasClass('ui-state-active') != true)
                        $('#accordion').accordion('activate', i);
                });
            });
        }
    }

    /* image swapping for adBadges */
    if ($('#adBadges').length > 0) {
        $('#adBadges img').hover(function () {
            swapCarouselImage(this)
        },
		function () {
		    swapCarouselImage(this)
		});
    }

    /* add zebra stripes to ULs -- currently (17/17/2009) only necesary on subModelDetail pages, options-and-specs page, and pricing and incentives page. some of these conditiosn overlap, so don't change to else if */

    if ($("div#container.subModelDetails").length > 0)
        $("div#container.subModelDetails #contentContainer ul.featuresList li:nth-child(even)").addClass("alt");
    if ($("div#container.optionsSpecifications").length > 0 || $("div#container.subModelDetailsOptionsSpecifications").length > 0)
        $("#contentContainer #accordion table tr:nth-child(even)").addClass("alt");
    if ($("div#container.pricingIncentives").length > 0 || $('.financeTypeSelector input').length > 0 ) {
        $("#contentContainer table > tbody tr:nth-child(even)").addClass("alt");
        $(".financeTypeSelector").css('visibility', 'visible');
        document.forms['pricingPageForm'].reset();
        $("div#container.pricingIncentives input, .financeTypeSelector input").click(function () {
            var num = this.name.replace(/financeType/, '')
            var id = '#' + this.value + 'Table' + num;
            var $el = $(id);

            if ($('.activeOVPPricingTable' + num).length > 0) {
                $('.activeOVPPricingTable' + num).hide().removeClass('activeOVPPricingTable' + num);
            }

            $el.addClass('activeOVPPricingTable' + num).show();
        });
    }

    // Dirty Opera hack for voken images
    if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { //test for Opera/x.x or Opera x.x (ignoring remaining decimal places);
        if ($('#overviewPromoVoken').length > 0) {
            document.getElementById("overviewPromoVoken").style.top = "19px";
            document.getElementById("overviewPromoVoken").style.left = "995px";
        }
    }
});

function loadGlossary(){
	$("a.glossaryItem").css('display','inline');
	$('a.glossaryItem').cluetip({
	  hoverClass: 'highlight',
	  sticky: false,
	  closePosition: 'top',
	  showTitle: false,
	  waitImage: true,
	  closeText: ''
	});
	$('a.glossaryItem').click(function(event){
		event.preventDefault();
     });

}

$(window).load(function () {
	//test for Opera/x.x or Opera x.x (ignoring remaining decimal places); AND for iPad (don't show glossary for iPad)
	if (!/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent) && !(navigator.userAgent.match(/iPad/i) != null)) { 
		if ($('.glossary').length > 0) {
			if (thisURL.indexOf('options-and-specifications') != -1)
				glossaryPlugin('options-and-specifications');
			
			if (thisURL.indexOf('overview') != -1 || thisURL.indexOf('models') != -1 || thisURL.indexOf('accessories') != -1 || thisURL.indexOf('pricing-and-incentives') != -1 || thisURL.indexOf('highlights') != -1 || thisURL.indexOf('warranties') != -1 || thisURL.indexOf('real-reactions') != -1 || thisURL.indexOf('model-detail') != -1)
				glossaryPlugin('global');
			
			$(".glossary").each(function (i) {
				var glossaryHTML = $(this).html();
				var thisID = $(".glossary").attr('class');
				thisID = thisID.replace(/glossary g_1_/,'');
				thisID = "/gm/"+thisLangLong+"/getxmlcontent?section=1&amp;id="+thisID;				
				$(this).replaceWith('<span style="white-space:nowrap;" class="glossaryElement"><a class="glossaryItem" href="'+thisID+'" rel="'+thisID+'"><img src="/images/common/glossaryIcon.gif" alt="i" /></a>'+glossaryHTML+'</span>');
			});
			
			$.ajax({
			type: "GET",
			url: "/js/common/cluetip/jquery.cluetip.js",
			dataType: "script",
			cache: true,
			timeout: 2000,
			success: function(msg){
				setTimeout ( "loadGlossary()", 1000 ); 
				}
			});
			
		}
	}
});

function galleryCarousel_itemLoadCallback(carousel, state){
	if(state == "init"){
		$("#galleryCarousel").css("visibility","visible");
	}
}

function galleryCarousel_initCallback(carousel) {
	if (thisURL.indexOf('gallery-fabric-interior') != -1) {
		var borderPosition=1+document.getElementsByName("firstList").length*76-76;
		document.getElementById('galleryCarousel').style.backgroundPosition=borderPosition+"px bottom";
	}
	jQuery('#photoNext').bind('click', function() {
		var cur_image = $('#vehicle').attr('src').replace(/_big/, '');
		
		//Get the attr attribute of the <li> after the current image becoz it comtains the Video path to akamai
		if(akamai_vdo==true){
			var item=$(".curPhoto").next("li").attr("alt");		
		}
		
		
		//small img can be jpg or gif. big img is always jpg
		if ($('#galleryCarousel img[src*='+cur_image.split('/').pop()+']').parent().parent().attr("class")){
			var list_item = $('#galleryCarousel img[src*='+cur_image.split('/').pop()+']').parent().parent().attr("class").match(/\d+/);
		}
		else{
			cur_image = cur_image.replace(/.jpg/, '.gif');
			var list_item = $('#galleryCarousel img[src*='+cur_image.split('/').pop()+']').parent().parent().attr("class").match(/\d+/);
		}
		if (list_item != carousel.size()) { // if carousel is not at end, change big image and scroll carousel ahead 1
			toggleActiveCarouselItem($('#galleryCarousel li.jcarousel-item-'+list_item), "off");
			list_item++;
			if(akamai_vdo==true){
				toggleActiveCarouselItem(item, "on", true);
			}else{
				toggleActiveCarouselItem($('#galleryCarousel li.jcarousel-item-'+list_item), "on");
			}
			
			// 2009/08/28 -- MC to accomodate .gif thumbnails
			//cur_image = $('#galleryCarousel li.jcarousel-item-'+list_item+' img').attr('src').replace(/(\d+).jpg/, 'big_$1.jpg');
			cur_image = $('#galleryCarousel li.jcarousel-item-'+list_item+' img').attr('src').replace('.gif', '.jpg');
			cur_image = cur_image.replace(/(\d+).jpg/, 'big_$1.jpg');
			
			changeBigImage(cur_image);
			carousel.scroll(jQuery.jcarousel.intval(list_item));
		}
		return false;
	});
	jQuery('#photoPrev').bind('click', function() {
		var cur_image = $('#vehicle').attr('src').replace(/_big/, '');
		
		//Get the attr attribute of the <li> after the current image becoz it comtains the Video path to akamai
		if(akamai_vdo==true){
			var item=$(".curPhoto").prev("li").attr("alt");		
		}
		
		if ($('#galleryCarousel img[src*='+cur_image.split('/').pop()+']').parent().parent().attr("class")){
			var list_item = $('#galleryCarousel img[src*='+cur_image.split('/').pop()+']').parent().parent().attr("class").match(/\d+/);
		}
		else{
			cur_image = cur_image.replace(/.jpg/, '.gif');
			var list_item = $('#galleryCarousel img[src*='+cur_image.split('/').pop()+']').parent().parent().attr("class").match(/\d+/);
		}
		
		if (list_item != 1) { // if carousel is not at beginning, change big image and scroll carousel back 1
			toggleActiveCarouselItem($('#galleryCarousel li.jcarousel-item-'+list_item), "off");
			list_item--;
			
			if(akamai_vdo==true){
				toggleActiveCarouselItem(item, "on", true);
			}else{
				toggleActiveCarouselItem($('#galleryCarousel li.jcarousel-item-'+list_item), "on");
			}
			
			// 2009/08/28 -- MC to accomodate .gif thumbnails
			//cur_image = $('#galleryCarousel li.jcarousel-item-'+list_item+' img').attr('src').replace(/(\d+).jpg/, 'big_$1.jpg');
			cur_image = $('#galleryCarousel li.jcarousel-item-'+list_item+' img').attr('src').replace('.gif', '.jpg');
			cur_image = cur_image.replace(/(\d+).jpg/, 'big_$1.jpg');
			
			changeBigImage(cur_image);
			carousel.scroll(jQuery.jcarousel.intval(list_item));
		}
		return false;
	});
	$('#galleryCarousel li:first-child').addClass('curPhoto');
};

function swapCarouselImage(this_image){
	
	var old_image = $(this_image).attr('src');
	if (old_image.indexOf('_off.') != -1 || old_image.indexOf('_on.') != -1) {
		if (old_image.indexOf('_off.') != -1){
			var newImg = old_image.replace(/_off./,"_on.");
		}
		else if (!$(this_image).parent().parent().hasClass('curPhoto')) {
			var newImg = old_image.replace(/_on./,"_off.");
		}
		$(this_image).attr('src',newImg);
	}
}          

function loadFlashGallerySWF(newFlashVideo){
	var vidType = "flv";
	
	if (newFlashVideo.indexOf('_threesixty_') != -1){
		vidType = "qtvr";
	}
	
	var flashDiv = document.getElementById('flashDiv');
	if ( flashDiv ) {
		flashDiv.parentNode.removeChild(flashDiv);
	}
	
	var fd  = document.createElement('div');
	fd.setAttribute('id', 'flashDiv');
	
	var dmc = document.getElementById('designMainContent');
	dmc.appendChild(fd);
	
	
	var flashFile = newFlashVideo.replace(/\.jpg/, '.swf');
	flashFile = flashFile.replace(/\.gif/, '.swf');
	flashFile = flashFile.replace(/images/, 'media');
	var params = {wmode: "transparent",scale: 'noscale',salign: 'TL',menu: 'false'};
	
	swfobject.embedSWF("/media/vehicles/common/player.swf?vidPath=" + flashFile + "&vidType=" + vidType, "flashDiv", "740", "365", "9.0.0", "", "", params, "", function(e) {
		if ( e.success ) {
			document.getElementById('vehicle').style.display = 'none';
		}
	});
}

function loadAkamaiVideo(newAkamaiVideopath){
	
	var flashDiv = document.getElementById('flashDiv');
	if ( flashDiv ) {
		flashDiv.parentNode.removeChild(flashDiv);
	}
	
	var fd  = document.createElement('div');
	fd.setAttribute('id', 'flashDiv');
	
	var dmc = document.getElementById('designMainContent');
	dmc.appendChild(fd);
	
	
	var flashvars = {};
	flashvars.filePath = "mp4:"+newAkamaiVideopath;
	flashvars.autoPlay= "false";
	flashvars.wmode = "transparent";
	flashvars.menu = "false";
	flashvars.scale = "noscale";
	flashvars.allowfullscreen = "false";
	flashvars.allowscriptaccess = "always";						
	var attributes2 = {};
	attributes2.id = "flashContainer2";
	attributes2.name = "flashContainer2";
	attributes2.wmode = "transparent";
	
	
	swfobject.embedSWF("/media/vehicles/common/main.swf", "flashDiv", "740", "366", "9","expressInstall.swf", flashvars,  attributes2,"",function(e) {
		if ( e.success ) {
			document.getElementById('vehicle').style.display = 'none';
		}
	});	
		
	$('#caption').hide();
	
}

function changeBigImage(new_src) {
	$('#vehicle').attr("src", new_src.replace(/_on/, ''));
	if ((new_src.indexOf('_threesixty_') != -1) || (new_src.indexOf('_videos_') != -1)){
		if(akamai_vdo==false){
			loadFlashGallerySWF(new_src);
		}
	}
	

	var old_src = new_src.split('/').pop().replace(/_big/, '').split('.')[0]; // isolate the 'big' file name, and ignore the file extension
	var active_list_item = $('#galleryCarousel img[src*='+old_src+']').parent().parent().attr("class").match(/\d+/);	
	if (active_list_item == 1) {
		$('#photoPrev a').addClass('disabled');
		$('#photoNext a').removeClass('disabled');
	}
	else if (active_list_item == $('#galleryCarousel').children().length) {
		$('#photoNext a').addClass('disabled');
		$('#photoPrev a').removeClass('disabled');
	}
	else {
		$('#photoPrev a').removeClass('disabled');
		$('#photoNext a').removeClass('disabled');
	}
	return true;
}

function toggleActiveCarouselItem(list_item, flag, akamaivdo) {
	
	//If not defined then set as false
	if ( akamaivdo === undefined ) {
		akamaivdo=false;
	}
	
	var captionTitle, captionDesc;
	if (flag == "on") {
		if(akamaivdo==true){ //If this is Akamai video
				$("li[alt='"+list_item+"']").addClass('curPhoto'); //To outline the parent <li> on select
				loadAkamaiVideo(list_item);
		}else{
			$(list_item).find('img').attr('src', $(list_item).find('img').attr('src').replace(/_off/, '_on'));
			$(list_item).addClass('curPhoto');
			
			var separatorPosition = $(list_item).find('img').attr('alt').indexOf(". ");
			var captionTitle = "";
			var captionDesc = "";
			var imageTitle = "";
			var isWallpaper = false;

			if (separatorPosition != -1) {
				captionTitle = $(list_item).find('img').attr('alt').substring(0,(separatorPosition));
				captionDesc = $(list_item).find('img').attr('alt').substring((separatorPosition+1));
				imageTitle = captionTitle + "." + captionDesc;
			}
			else {
				captionTitle = $(list_item).find('img').attr('alt');
				imageTitle = captionTitle;
			}
			
			// For gallery wallpaper images, override the default description with download links		
			if($(list_item).children("a.thumbnail").hasClass("gallery-wallpaper")) {
				isWallpaper = true;
				captionDesc = (location.href.indexOf("/english/") != -1) ? "Choose your size:<br/>" : "Choisissez la taille:<br/>";
				captionDesc += "<a href=\"" + $(list_item).find('img').attr('src').replace(/.jpg/, '_800.jpg') + "\" style=\"color:#E3982B;\" target=\"_blank\">800x600</a>&nbsp;";
				captionDesc += "<a href=\"" + $(list_item).find('img').attr('src').replace(/.jpg/, '_1024.jpg') + "\" style=\"color:#E3982B;\" target=\"_blank\">1024x768</a>&nbsp;";
				captionDesc += "<a href=\"" + $(list_item).find('img').attr('src').replace(/.jpg/, '_1280.jpg') + "\" style=\"color:#E3982B;\" target=\"_blank\">1280x1024</a>&nbsp;<span style=\"white-space: nowrap;\"><a title=\"\" style=\"display: inline;\" class=\"glossaryItem\" href=\"/gm/"+thisLangLong+"/getxmlcontent?section=1&amp;id=25\" rel=\"/gm/"+thisLangLong+"/getxmlcontent?section=1&amp;id=25\"><img src=\"/images/common/glossaryIcon.gif\" alt=\"i\"></a>&nbsp;</span>";
			}
			
			$('p#captionTitle').html(captionTitle);
			$('p#captionDesc').html(captionDesc);
			$('img#vehicle').attr({alt: imageTitle, title: imageTitle});
			if(isWallpaper){
				loadGlossary();
			}
		}
	}
	else if (flag == "off") {
		$(list_item).find('img').attr('src', $(list_item).find('img').attr('src').replace(/_on/, '_off'));
		$(list_item).removeClass('curPhoto');
	}
	else if (flag == "clearAll") {
		$('#galleryCarousel li').removeClass('curPhoto');
		var images = $('#galleryCarousel li img');
		var images_len = $('#galleryCarousel li img').length;
		for(var i=0; i<images_len; i++) {
			if($(images[i]).attr('src').indexOf('_on.') != -1) 
				$(images[i]).attr('src', $(images[i]).attr('src').replace(/_on./, '_off.'));
		}
	}
	return true;
}

function equalizeModelDivHeight () {
	// doesn't work perfectly in webkit-based browsers, but close
	var max_height = 0;
	$('#modelsCompare div.model').each( function() {
		if ($(this).height()>max_height) {
			max_height = $(this).height();
		}
	}).find('div.modelInfoInner').each( function() {
		var gap = max_height - $(this).parents('div.model').height();
		if (gap > 0)
			$(this).css({'height':($(this).height() + gap)+'px'});
	});
}

function setCookie(name, value, expires, path, domain, secure) {
	var curCookie = name + '=' + escape(value) + ((expires) ? '; expires=' + expires.toGMTString() : '') + ((path) ? '; path=' + path : '') + ((domain) ? '; domain=' + domain : '') + ((secure) ? '; secure' : '');
	document.cookie = curCookie;
}

// Pop-up

	function openWin(url, popWidth, popHeight, popScroll, popStatus, popWin) {
		var ie5 = (document.all && document.getElementbyID) ? false : true;
		var isMac = (navigator.appVersion.indexOf("Mac") == -1) ? false : true;
		var win, win2;

		var winName =  "popup";
		if (popWin != null)
		{
			winName = popWin;
		}
		var statusBar = popScroll;

		if (popStatus != null) {
			statusBar  = popStatus;
			if (!ie5 && !ns && isMac) { popHeight += 18; }
		}
		win=window.open(url, winName, 'width=' + popWidth + ',height=' + popHeight + ',screenX=25,screenY=150,left=25,top=150,scrollbars=' + popScroll + ',resize=no,status=' + statusBar + '');
		if (win.opener == null) win.opener = self;
		win.focus();
	}

function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	}
	else begin += 2;
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}

/////////////////////////////////////////////////////////////////////////////////////////////

function switchTeaser(year, make, model) {
    var slideUp = 0;

    // Map model vars to actual folder strcuture
    make = make.toLowerCase();
	vehicleMake = make;
	
    model = model.replace(/ /g, '');
    model = model.toLowerCase();
    if (model == "coup\u00e9cts" || model == "ctscoupe") 
        model = 'cts';
    else if (model == "cts5portes" || model == "ctssportwagon") 
        model = 'cts-wagon';
	else if (model == "familialesportcts" || model == "ctssportwagon") 
        model = 'cts-wagon';	
    else if (model == "sierrahd") 
        model = 'sierra-hd';
    else if (model == "sierra") 
        model = 'sierra_hybrid';

    //alert(year);
    //alert(make);
    //alert(model);

    if ((make == 'cadillac' && model == 'srx') || (make == 'cadillac' && model == 'cts') || (make == 'cadillac' && model == 'cts-wagon') || (make == 'buick' && model == 'regal') || (make == 'buick' && model == 'lacrosse') || (make == 'gmc' && model == 'sierra-hd') || (make == 'gmc' && model == 'sierra_hybrid') || (make == 'gmc' && model == 'terrain') || (make == 'chevrolet' && model == 'silveradohd') || (make == 'chevrolet' && model == 'cruze') || (make == 'chevrolet' && model == 'orlando') || (make == 'chevrolet' && model == 'volt') || (make == 'chevrolet' && model == 'sonic')) 
    {
        //$('#overviewTop').css('background', 'url(none)');
        //$('#vehiclePricing').css('display', 'none');

        var flashvars = {};
        flashvars.lang = thisLang;
        flashvars.filePath = "/media/vehicles/current/" + make + "/" + model + "/teaser/";

        var params = {};
        params.wmode = "transparent";

        var launchPath = "/media/vehicles/current/common/teaser/";
		if(make == 'chevrolet') {
			swfobject.embedSWF(launchPath+"chev_ovp_player.swf?v=3", "flashContent", "990", "340", "9.0.0", false, flashvars, params);
		} else {
			swfobject.embedSWF(launchPath+"ovp_player.swf?v=3", "flashContent", "990", "340", "9.0.0", false, flashvars, params);
		}
        
        swfobject.addDomLoadEvent(function () { setupSWFObjectFocus(); });
    }
}

function from_flash_set_focus() {
    // called by the flash once it's been loaded
    setupSWFObjectFocus();
}

// These two functions are called by Flash when the user rolls over a button and shows a slide. 
// OR when they go back to the default image. (close [-])
function hide_vehicle_pricing() {
    $('#vehiclePricing').css('display', 'none');
    if (vehicleMake != "chevrolet") {
        slideUp = 1;
        $('#pageTools').css('display', 'none');
    }
}

function show_vehicle_pricing() {
    $('#vehiclePricing').css('display', 'block');
    if (vehicleMake != "chevrolet") {
        slideUp = 0;
        setTimeout("if (!slideUp) document.getElementById('pageTools').style.display='block'", 500);
    }
}


function setupSWFObjectFocus() {
    // called in <body onLoad="">
    // also called by swfobject.addDomLoadEvent
    // also called by flash when it's been loaded
    var swf = document.getElementById("flashContent");
    swf.focus();
    //onkeydown = swf.focus();
}

/////////////////////////////////////////////////////////////////////////////////////////////

function emailDialog(lang) {	
	// Language variables
	var dialogTitle = (lang == "english") ? "Email a Friend" : "Dites-le &#xE0; un ami";
	var errorEmailMsg = (lang == "english") ? "Invalid email address" : "Addresse courriel invalide";
	var errorReqMsg = (lang == "english") ? "This field is required" : "Champ obligatoire";
	//Captcha Input
	var captchaMessageInput = "<input type=\"text\" id=\"captcha-response\" name=\"j_captcha_response\">";
	$("body").append("<div id=\"dialog\" title=\"" + dialogTitle + "\"></div>");
	$.ui.dialog.defaults.bgiframe = true;
	$(function() {
		$.ajax({
			url: "email-form",
			cache: false,
			success: function(html){
				
				$("#dialog").append(html);
				$('#emailReturnMsgSuccess').hide();
				$('#emailReturnMsgFail').hide();
				//Force Reload JCaptcha Image
				d = new Date();
			    $("#captcha").attr("src", "/gm/jcaptcha?"+d.getTime());
				$("#dialog").dialog({ 
					buttons: {
						"Send": function() { $("#EmailForm").submit(); },
						"Cancel": function() { $(this).dialog("close"); }
					},
					close: function(event, ui) {
						$("#dialog").remove(); // remove dom elements upon closing the dialog
					},
					modal:true, 
					width:700,
					zIndex:9999
				});
				if(lang == "french") { // 
					$('#dialog').dialog('option', 'buttons', { 
						"Envoyer": function() { $("#EmailForm").submit(); },
						"Annuler": function() { $(this).dialog("close"); }
					});	
				}
				$("#EmailForm").validate({
					messages: {
						from_name: { required: errorReqMsg },
						to_email_1: { email: errorEmailMsg, required: errorReqMsg },
						to_email_2: { email: errorEmailMsg },
						to_email_3: { email: errorEmailMsg },
						to_email_4: { email: errorEmailMsg }
					},
					submitHandler: function(html) {
						$.ajax({
							type: "GET",
							data: "from_name=" + $("#from_name").val() + "&j_captcha_response=" + $("#captcha-response").val() + "&to_email_1=" + $("#to_email_1").val() + "&to_email_2=" + $("#to_email_2").val() + "&to_email_3=" + $("#to_email_3").val() + "&to_email_4=" + $("#to_email_4").val() + "&url=" + location.href,
							url: "/gm/"+lang+"/sendemail",
							dataType: "html",
							success: function(data, textStatus) {
							//it could be other way to check return value
							if(data.length>10&&data.length<50)
							{
								//Force Reload JCaptcha Image
							   d = new Date();
							   $("#captcha").attr("src", "/gm/jcaptcha?"+d.getTime());
                               //Empty input value and other error message							   
							   $("#captchaMessage").html(captchaMessageInput);
							   //Add new error message
							   $("#captchaMessage").append(data).css("color", "red");
							}
								
							else{	
								$("#EmailForm").hide();
								$("#dialog").dialog('destroy');
								$('#emailReturnMsgSuccess').show();
								$("#dialog").dialog({
									buttons: {
										"OK": function() { $(this).dialog("close"); }
									},
									close: function(event, ui) {
										$("#dialog").remove(); // remove dom elements upon closing the dialog
									},
									modal:true,
									zIndex:1500000
								});}
							},
							error: function(XMLHttpRequest, textStatus, errorThrown) {
								$("#EmailForm").hide();
								$("#dialog").dialog('destroy');
								$('#emailReturnMsgFail').hide();
								$("#dialog").dialog({
									buttons: {
										"OK": function() { $(this).dialog("close"); }
									},
									close: function(event, ui) {
										$("#dialog").remove(); // remove dom elements upon closing the dialog
									},
									modal:true,
									zIndex:1500000
								});
							}
						});
					}
				});
			}
		}); 
	});
}

// REAL REACTIONS SHOW HIDDEN REACTIONS
function showHiddenRealReactions(){
	$(".showRealReactions").css("display","none");
	$("#hiddenRealReactions").slideDown();
	return false;
}

/////////////////////////////////////////////////////////////////////////////////////////////

function hideChatButtton(){
	document.getElementById("chatFooter").style.display = "none";
	return false;
}

/////////////////////////////////////////////////////////////////////////////////////////////

function glossaryPlugin(page){
	var glossItemsArray = {};
	$(".glossary").each(function (i) {
		cid = $(this).attr('class').replace(/glossary /,'');
		glossItemsArray[cid] = true;
	});

	switch(page){
		case "options-and-specifications":	// OPTION AND SPECYFICATIONS 
					$(".specData").each(function (i, table) {
						$.each(glossItemsArray, function(key, value) { 
							$("#" + table.id + " ." + key + ":gt(0)").attr("class","nonGlossary");
						});
					});
					break;
		case "global":	// FOR ALL OTHER PAGES
					$.each(glossItemsArray, function(key, value) { 
							$("body ." + key + ":gt(0)").attr("class","nonGlossary");
					});
					break;

	}
	
}

function changeVideoLang(akamaiVideoName){
	//Set vdo name as per the page language (if not already done)
	if(akamaiVideoName.indexOf("en_")!= -1 && thisLang=='fr'){
		akamaiVideoName=akamaiVideoName.replace("en_", "fr_");
	}else if(akamaiVideoName.indexOf("fr_")!= -1 && thisLang=='en'){
		akamaiVideoName=akamaiVideoName.replace("fr_", "en_");
	}
	
	return akamaiVideoName;
}
