(function($) {
    $.fn.jAddToFavorites = function(options) {
        var defaults = $.extend(opts = {
            language: {
                '': 'Press [functionButton] + D keys to bookmark this page'
				,'msie': 'Click to add to Favourites'
				,'firefox': 'Click to bookmark this page'
            },
            functionButton: ['CTRL', 'CMD']
            // Function key format: ['Windows key', 'Macintosh key']
        }, options);
              
        return this.each(function() {
			try {
				$(this).click(addToBrowserclicked);
				if ($.browser.mozilla) { // Firefox
					$(this).html(getKeyMessage('firefox'));
				} else if($.browser.msie) { // IE Favorite
					$(this).html(getKeyMessage('msie'));
				} else {
					throw error;
				}
			} catch (error) {
				$(this).html(getKeyMessage('')).addClass("gWht")
			}

        });
        
		function addToBrowserclicked(e){
			e.preventDefault();
			var docUrl = window.location.href; // Get current URL from the browser location.
        	var docTitle = document.title; // Get the current title from the document.
			try {
				if (window.sidebar && $.browser.mozilla) { // Firefox
					window.sidebar.addPanel(docTitle, docUrl,"");
				} else if($.browser.msie) { // IE Favorite
					window.external.AddFavorite( docUrl, docTitle); 
				} else {
					throw error;
				}
			} catch (error) {
				alert(getKeyMessage(''));
			}
		}
		 
		function getKeyMessage(tt){
			var alertText = opts.language[tt];
			var m = (/mac/.test(navigator.platform.toLowerCase() == 'mac'))?1:0
			alertText = alertText.replace('[functionButton]', opts.functionButton[m]);
			return alertText;
		}  
    }; 
})(jQuery);


// requires /jquery/flowplayer/jquery.tools.min.js
var _gaq = _gaq || [];
var overlay = {overlayDiv:null,api:null,content:null,onclose:null,ajaxContentURL:null,ajaxContentData:null,localhost:null,onOpen:null,disabled:false,showWhilstAjaxLoads:false}

overlay.init = function(){
	with(overlay){
		$("body").append('<div id="defaultOverlay" class="defOverly w750"><div class="contentWrap"></div></div>');
		api = $("#defaultOverlay").overlay({
			//top: '',
			mask: {
				color: '#000',
				loadSpeed: 200,
				opacity: 0.5
			},
			onBeforeLoad:overlay.onBeforeLoad,
			onLoad:overlay.onLoad,
			onBeforeClose:overlay.onBeforeClose,
			//closeOnClick: false,
			fixed:true,
			effect: 'apple',
			api:true
		});
		overlayDiv = api.getOverlay();
		content = overlayDiv.find(".contentWrap");
		localhost = (window.location.toString().indexOf('/buyacar/')>-1)? "/buyacar":"";
		overlay.resize();
		$(window).resize(overlay.resize);
	}
}

overlay.show = function(){
	if(overlay.overlayDiv==null)overlay.init();
	if(overlay.disabled)return;
	overlay.api.load();
	overlay.content.find('.overlayClose').click(overlay.closeButtonClicked2);
	overlay.content.find('.addToFavorites').jAddToFavorites();
	if(typeof(quoteId)!='undefined')overlay.content.find('#popup_quoteId').val(quoteId);
	if(overlay.content.html().indexOf("form")>0)param.addPartnerKeyToForms();
}

overlay.close = function(e){
	// close overlay.onclose will be run which will halt the close
	overlay.api.close(e);
	return false;
}

overlay.hide = function(){
	if(overlay.overlayDiv==null) return;
	//close popup without running code in overlay.onclose
	var e = $.Event();
	e.overlayHide = true;
	overlay.api.close(e);
}

overlay.setMsg = function(content,title){
	if(overlay.overlayDiv==null)overlay.init();
	overlay.content.html(content);
}

overlay.setURL = function(url,data,openOverlay){
	if(overlay.overlayDiv==null)overlay.init();
	overlay.ajaxContentURL = url;
	overlay.ajaxContentData = data;
	overlay.showWhilstAjaxLoads = true;
	if(openOverlay)overlay.show();
	return false;
}

overlay.onBeforeClose = function(e){
	//overlayHide is set in overlay.hide() only
	if(!e.overlayHide && overlay.onclose!=null){
		var c = overlay.onclose;
		overlay.onclose=null;
		eval(c);
		return false;
	}
	_gaq.push(['_trackEvent', 'popup', 'closed']);
}

overlay.closeButtonClicked2 = function(e){
	overlay.close(e);
	return false;
}

overlay.onBeforeLoad = function(){
	with(overlay){
		if(ajaxContentURL == null) return;
		if(ajaxContentURL.indexOf("http")==-1)ajaxContentURL=localhost + ajaxContentURL;
		overlay.setMsg("LOADING.. please wait");
		content.load(ajaxContentURL, ajaxContentData, ajaxContentLoaded);
		return showWhilstAjaxLoads;
	}
}

overlay.onLoad = function(){
	overlay.resize();
	if(overlay.onOpen!=null)eval(overlay.onOpen);
	_gaq.push(['_trackEvent', 'popup', 'opened']);
}

overlay.resize = function(){
	with(overlay){
		if(!api.getConf().fixed)return;
		var sw = $(window).width();
		disabled=(sw<670);
		if(typeof(api.isOpened()) != "boolean" 
				|| !api.isOpened()
				|| !overlayDiv.data("img"))return;
		var top = content.offset().top - $(window).scrollTop();
		var sh= $(window).height();
	/*	if(top<20  || top>(sh/2)){
		overlayDiv.css("top","20px");
			overlayDiv.data("img").css("top","20px");
			top=20;
		}	*/	
		var maxHeight = (sh-top-30-10)+"px"; //30 is the padding
		if(disabled)hide();
		content.css("max-height",maxHeight);
	}
}

overlay.ajaxContentLoaded = function(){
	with(overlay){
		ajaxContentURL=null;
		ajaxContentData=null;
		var c = $.trim(content.html())
		if(c.length>10){
			//replace the word car
			if(typeof(genericDescription)=="string" && genericDescription!="car" && c.indexOf(" car")>-1){
			 setMsg(c.replace(/ car/g," "+genericDescription))
			}
			if(c.indexOf("<!--javascript:saveQuote.show()-->")>-1){
				saveQuote.show();
			}else{
				show();
			}
		}else{
			hide();	
		}
	}
}

overlay.defOverlay = function(){
	$('.defOverlay').click(function(){
		with(overlay){
			ajaxContentURL = this.href;
			ajaxContentData=null;
			onclose = null;
			showWhilstAjaxLoads = true;
			show();
			return false;
		}	
	});
}
/*
* quote assistant script is below
*/

//if completedAction in query string show popup
function checkForCompletedAction(){
	if(typeof(completedAction)=="undefined")return false;
//	if(param.cookie("completedAction")==completedAction)return false;
//	param.cookie("completedAction",completedAction);
	completedAction = completedAction.replace("_newlySaved","");
	var usp = (typeof(userSessionPresent) == "boolean" && userSessionPresent == false);
	showQuoteHelp(completedAction);
	return true;
}

function showBookmarkAlertAction(){
	if(typeof(showBookmarkAlert)=="undefined")return false;
	if(showBookmarkAlert)showQuoteHelp("showBookmarkAlert");
}


function showQuoteHelp(txt){
	if(typeof(txt)=="undefined" || txt=='')return;
	_gaq.push(['_trackEvent', 'popup', 'quote assistant requested', txt]);
	with(overlay){
		ajaxContentURL = "/AJAXSiteContent.jhtml";
		ajaxContentData={key:"QA"+txt};
		onclose = null;
		overlay.showWhilstAjaxLoads = false;
		show();
	}
	return false;	
}
$(document).ready(function() {
	checkForCompletedAction();
	showBookmarkAlertAction();
// enable the following line if you want the savequote button to open the register light dialog box.
//	saveQuote.buttonOpenPopup();
	overlay.defOverlay();
});

/*
* list signin and save quote ###############
*/

var saveQuote = {}

saveQuote.buttonOpenPopup = function(){
	var usp = (typeof(userSessionPresent) == "boolean" && userSessionPresent == false);
	if(usp){
		var btn = $('#saveQuoteBtn');
		btn.click(function(e){
			showQuoteHelp('newquote');
			return false;			   
			});
	}
}

saveQuote.show = function(){
	var btn = $('#saveQuoteBtn');
	if(btn.length>0){
		var usp = (typeof(userSessionPresent) == "boolean" && userSessionPresent == false);
		_gaq.push(['_trackEvent', 'popup', 'save quote box is shown', ((usp)?"sign up form shown":"user is already registered so save quote button only is shown")]);
		var squrl = overlay.localhost + ((usp)?"/secureajax/AJAXQuoteSave.jhtml":"/AJAXSiteContent.jhtml?key=QAnewquote_saveQuoteButton");
		$.ajax({
			url:squrl ,
			success:saveQuote.ajaxFormLoaded
		  });
	}else{
		overlay.show();
	}
}

saveQuote.ajaxFormLoaded = function(data,res){
	with(overlay){
		if(res=="success"){
			var cc = content.html();
			cc = cc.replace("<!--javascript:saveQuote.show()-->",data); 
			setMsg(cc);
			content.find('.btnRight').replaceWith("<a href='#' onclick='return overlay.closeButtonClicked2()'  class='nosave'>To continue to view your quote without saving it - click here</a>");
			onOpen = "sign.init()";
			show();
		}
	}
}














