var http = null;
var isAjaxRequestFinished = true;
var busyBox = null;

function createRequestObject() {
  var ro;
  var browser = navigator.appName;
  if(browser == "Microsoft Internet Explorer"){
   ro = new ActiveXObject("Microsoft.XMLHTTP");
  } else{
   ro = new XMLHttpRequest();
   browser = "other";
  }
  return ro;
}

function isDefined(variable)
{
    return (typeof(variable) == 'undefined')? false: true;
}

function sndReq(url, callbackfunction, async, useBusyBox) {
 if (http==null) http = createRequestObject();
  if (async == null) async = true;
  if (useBusyBox == null) useBusyBox = false;
  
  if (useBusyBox)
  {
	isAjaxRequestFinished = false;
	setTimeout("displayBusyBox();", 500);
  }

 http.open('get', encodeURI(url + '&random=' + Math.random()), async);
 http.onreadystatechange =  function () {
		if (typeof(http) != 'undefined')
		{
			if (http.readyState == 4) 
			{
				if (useBusyBox)
				{
					isAjaxRequestFinished = true;
					if (busyBox != null)
						busyBox.Hide();
				}
			eval(callbackfunction);
		}
		}
	}; 
 http.send(null);
}

function displayBusyBox()
{
	if(! isAjaxRequestFinished)
		if (busyBox != null)
			busyBox.Show();
}

function addEvent(obj, evType, fn, useCapture){
  if (obj == null)
    return false;
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be attached");
  }
}

function removeEvent(obj, evType, fn, useCapture){
  if (obj.removeEventListener){
    obj.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.detachEvent){
    var r = obj.detachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
}

function addLoadEvent(func)
{	
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = func;
	} else {
		window.onload = function(){
		oldonload();
		func();
		}
	}
}

function checkEvent( eventObj, eventKeyCode )
{
	if( !eventObj )
	{
		eventObj = window.event;
	}
	
	if( (eventObj.which && eventObj.which == eventKeyCode) || (eventObj.keyCode && eventObj.keyCode == eventKeyCode) )
    {
		return true;
	} 
    else 
    {
		return false;
	}
}



function pausecomp(millis)
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < millis);
} 



 

/* Search-form */
function fillSelectsWithOptions(elid,optstring,enable) {
	// due to bug in IE we can't just use innerHTML of an select element 
	// -> http://support.microsoft.com/kb/276228
	var el = document.getElementById(elid);
        clear_options(el);
	opts = optstring.split('|');
	for(i=0;i<opts.length-1;i++) {	    
		var splitParts = opts[i].split(':');
		var displayName = trim(splitParts[0]);
		//alert(displayName);
		displayName = displayName.replace("###","   ");
		var optionValue = trim(splitParts[1]);
		optionValue = optionValue.replace("###","");
		optionValue = optionValue.replace(/^\s*|\s*$/g, "");

        if (displayName != '')
        {
            el.options[i+1] = new Option(displayName, optionValue);
        }
		
//		
//		var tmp = opts[i]; //.replace(/^\s*|\s*$/g, "");
//		var optionname = tmp.split(':')[0];	
//		if(optionname != '') el.options[i+1] = new Option(optionname ,tmp.split(':')[1]);
	}
    if( enable == null || enable == true )
    {
		el.disabled=false;
    }
    
}

function clear_options(el) {
	 for (i = el.options.length-1;i>0;i--) {
	  el.options[i] = null;
	 }
}
/* Filling and resetting the selectboxes in the searchform */
// Changing the "body_type_id" selected item
function body_type_id_change(ev) {
	var makeel  = document.getElementById("make_name");
	var modelel = document.getElementById("model_name");
	var bodytypeel = document.getElementById("body_type_id");
	var selectedvalue = bodytypeel.options[bodytypeel.selectedIndex].value;
	clear_options(makeel);
 	clear_options(modelel);
	
	makeel.disabled=true;
    modelel.disabled=true;
    sndReq("/default.aspx?alttemplate=ajaxresponse&action=getmakes&body_type_id="+selectedvalue,"fillSelectsWithOptions('make_name',http.responseText)");
}

function ajaxsearch(url) {
   sndReq(url,"ajaxsearch_load(http.responseText)"); 
}

function ajaxsearch_load(txt) {
    document.getElementById('main').innerHTML = txt;
}


function make_name_change(ev) {
	var makeel  = document.getElementById("make_name");
	var modelel = document.getElementById("model_name");
	var bodytypeel = document.getElementById("body_type_id");

	var selectedvalue = makeel.options[makeel.selectedIndex].value;
	var body_type_id = (bodytypeel != null ) ? bodytypeel.options[bodytypeel.selectedIndex].value : "";

	modelel.disabled=true;
 	clear_options(modelel);
 	sndReq("/default.aspx?alttemplate=ajaxresponse&action=getmodels&body_type_id=" + body_type_id + "&make_name="+selectedvalue,"fillSelectsWithOptions('model_name',http.responseText)");
}

/* CarAdDetails */
function initGallery() {
        if (!document.getElementsByTagName){ return; }
        var anchors = document.getElementsByTagName("a");
        for (var i=0; i<anchors.length; i++){
                var anchor = anchors[i];
                if( anchor.href ) {
						if( anchor.getAttribute("rel") == "gallerythumb" ) {
							anchor.onmouseover =  function () {
                                galleryThumb_mouseover(this);
                                return false;
							}
							
							anchor.onclick = function () {
								return false;
							}
						}
						/*
                        else if( anchor.getAttribute("rel") == "gallerylarge" ) {
							anchor.onclick =  function () {
                                galleryLarge_click(this);
                                //return false;
							}
                        }
                        */
                }
        }
}

function galleryThumb_mouseover(anchor) {
        document.getElementById("imgLarge").src = anchor.href;
}
/*
function galleryLarge_click(anchor) {
	anchor.href='#';
	openGallery(ad_car_id);
	return false;
}
*/

function openGallery(adid, displaytype) {
	if( displaytype == null) {displaytype = "";}
    selectedimage = 1;
    if (document.getElementById("imgLarge").src.split('?').length > 1)
	        selectedimage = document.getElementById("imgLarge").src.split('?')[1];
    window.open('/annonce-galleri?ad_car_id='+adid+'&selectedimage='+selectedimage+'&dt='+displaytype,'gallerywindow','height=763,width=964');
}

/* Car ad comparison*/
var compare_count = null;
var compare_ids = null;
function displayCarAdComparison( minCount, referer_node_id ) {
	//sndReq("?alttemplate=ajaxresponse&action=getCompareCarAds", "gotoCarAdComparison(window.location.search + '&compare_car_ids=' + http.responseText)");
	getCompareCount();
	if( minCount == null ) {minCount = 2;}
	if( referer_node_id == null ) {referer_node_id = "";}
	if( compare_count < minCount ) {
		alert("Du skal minimum markere " + minCount + " og maksimum 3 biler til sammenligning.");
	} else {
		sndReq("/default.aspx?alttemplate=ajaxresponse&action=getSearchQueryString&fs=1", "gotoCarAdComparison(http.responseText + '&redir_node_id=" + referer_node_id + "')");
	}
}

function gotoCarAdComparison( querystring ) {
	if( querystring.indexOf("?") < 0 ) {
		querystring = "?" + querystring;
	}
	window.location.href = "/find-din-bil/sammenlign-biler" + querystring + "&tab=comparecars";
}

function displayCompareCount() {
	getCompareCount();
	var elCompareCount = document.getElementById("comparecount");
	if( elCompareCount != null ) {
		elCompareCount.innerHTML = compare_count;
		document.getElementById("comparecount_footer").innerHTML = elCompareCount.innerHTML;
		document.getElementById("comparecounttext").innerHTML = compare_count != 1 ? "biler" : "bil";
		document.getElementById("comparecount_footertext").innerHTML = document.getElementById("comparecounttext").innerHTML;
	}
	
	var elTabCompareCount = document.getElementById("tabCompareCount");
	if( elTabCompareCount != null ) {
		elTabCompareCount.innerHTML = compare_count;
	}
}

function addCompareCarAd( ad_car_id, chkbox ) {
	getCompareCount();
	if( compare_count >= 3 ) {
		if( chkbox != null ) {chkbox.checked = false;}
		alert("Du kan maksimalt sammenligne 3 biler ad gangen.");
		return false;
	}
	else {
		setCompareCarAd( ad_car_id );
		compare_count += 1;
		displayCompareCount();
		return true;
	}
}

function remCompareCarAd( ad_car_id ) {
	//var compare_count = getCompareCount();
	setCompareCarAd( ad_car_id );
	compare_count -= 1;
	displayCompareCount();
}

function setCompareCarAd( ad_car_id ) {
	sndReq("/default.aspx?alttemplate=ajaxresponse&action=setCompareCarAd&ad_car_id=" + ad_car_id, "", false);
}

function getCompareCount() {
	if( compare_count == null ) {
		sndReq("/default.aspx?alttemplate=ajaxresponse&action=getCompareCarAdsCount&stamp=" + new Date().getTime() , "compare_count = parseInt(http.responseText)", false);
	}

}

function getCompareIds() {
	if( compare_ids == null ) {
		sndReq("/default.aspx?alttemplate=ajaxresponse&action=getCompareCarAds&stamp=" + new Date().getTime() , "compare_ids = http.responseText", false);
	}
}

/* Articlegallery */
function initArticleGallery() {
        if (!document.getElementsByTagName){ return; }
        var anchors = document.getElementsByTagName("a");
        for (var i=0; i<anchors.length; i++){
                var anchor = anchors[i];
                if( anchor.href ) {
						if( anchor.getAttribute("rel") == "gallerythumb" ) {
							anchor.onmouseover =  function () {
                                galleryThumb_mouseover(this);
                                return false;
							}
							
							anchor.onclick = function () {
								return false;
							}
						}
                        else if( anchor.getAttribute("rel") == "gallerylarge" ) {
							anchor.onclick =  function () {
                                ArticleGalleryLarge_click(this);
                                //return false;
							}
                        }
                }
        }
}

function ArticleGalleryLarge_click(anchor) {
	anchor.href="#";
	openArticleGallery();
	return false;
}

function openArticleGallery() {
    selectedimage = 1;
    if (document.getElementById("imgLarge").src.split('?').length > 1)
	        selectedimage = document.getElementById("imgLarge").src.split('?')[1];
    window.open('?&altTemplate=articlegallery&selectedimage='+selectedimage,'gallerywindow','height=660,width=770');
}

function openHelp( anchor )
{
	window.open(anchor.href,'helpwindow','height=660,width=770,scrollbars=1');
	return false;
}

function initSearch()
{
	if (!document.getElementsByTagName){ return; }
        var anchors = document.getElementsByTagName("a");
        for (var i=0; i<anchors.length; i++){
                var anchor = anchors[i];
                if( anchor.href && anchor.getAttribute("rel") == "calc_distance" ) 
                {
					anchor.onclick =  function () {
                        //displayEnterZipcode();
                        //setMouseCoordinatesByObject(this);
                        //displayOverMenu( "enterzipcode", -100, -30 );
						displayOverMenu( "enterzipcode", getAbsoluteLeftByObject(this)-100, getAbsoluteTopByObject(this)-30 );
                        document.getElementById("newzipcode").focus();
                        
                        return false;
					}
                }
        }
}

/* String functions */
function trim( str )
{
   return str.replace(/^\s*|\s*$/g,"");
}

function stripHtml(htstring)
{
    var re = new RegExp("(<script(.|\n)+?</script>)", "ig")
    var str = htstring.replace(re ,"");
    var result = str.replace(/(<([^>]+)>)/ig,"");
    return result;
    //return htstring.replace(/<script.+?</script>/ig,"").replace(/(<([^>]+)>)/ig,""); 
}

function validateZipcode( zipcode )
{
	zipcode = trim(zipcode);
	return ( zipcode.length == 4 && isNaN(zipcode) == false );
}

/* Control functions */

// gets selected value from <select> control
function getSelectedValue( selCtrl_name )
{
	ctrl = document.getElementById(selCtrl_name);
	if( ctrl.selectedIndex >= 0 )
		return ctrl.options[ctrl.selectedIndex].value;
	else
		return "";
}

// sets selected value in <select> control
function setSelectedValue( selCtrl_name, value )
{
	var i = 0;
	ctrl = document.getElementById(selCtrl_name);
	for( i=0; i<ctrl.options.length; i++ )
	{
		if( ctrl.options[i].value == value )
		{
			ctrl.selectedIndex = i;
			break;
		}
	}
}

/* Cookie functions */
function setCookie( name, value, expireDate, path )
{
	var cookieValue = "";
	if( name == null ) {name = "defaultcookie";}
	cookieValue = name + "=" + escape(value);
	if( expireDate != null )
	{
		cookieValue += ";expires=" + expireDate;
	}
	if(path)
	{
	    cookieValue += ";path=" + escape(path);
	}
	document.cookie = cookieValue;
}

function getCookie( name )
{
	if( name == null ) {name = "defaultcookie";}
	var cookies = document.cookie.split("; ");
	for (var i=0; i < cookies.length; i++)
	{
		// a name/value pair (a crumb) is separated by an equal sign
		var aCrumb = cookies[i].split("=");
		if (name == aCrumb[0]) 
			return unescape(aCrumb[1]);
	}

	return "";
}

function deleteCookie( name )
{
	
	var expire_date = new Date();
	expire_date.setFullYear(2005);
	
	setCookie( name, "", expire_date);
}

/* Positioning */
function getAbsoluteLeft(objectId) {
	// Get an object left position from the upper left viewport corner
	// Tested with relative and nested objects
	o = document.getElementById(objectId)
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	// Return left postion
	return oLeft
}

function getAbsoluteTop(objectId) {
	// Get an object top position from the upper left viewport corner
	// Tested with relative and nested objects
	o = document.getElementById(objectId)
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	// Return top position
	return oTop
}

/* Positioning */
function getAbsoluteLeftByObject(o) {
	// Get an object left position from the upper left viewport corner
	// Tested with relative and nested objects
	
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	// Return left postion
	return oLeft
}

function getAbsoluteTopByObject(o) {
	// Get an object top position from the upper left viewport corner
	// Tested with relative and nested objects
	
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	// Return top position
	return oTop
}

function convertToHtmlNumericCodes(inString) {
    var outString = "";
    var length = inString.length
    for(i=0; i<length; i++){
        outString+="&#"+inString.charCodeAt(i)+";"
    }
    return outString;
}


function BuildURLFromRelativePath(RelativePart)
{
  return 'http://' + window.location.host + RelativePart;
}

Date.prototype.getNextSunday = function(weekOffset) {
var dayOffset = 0;
if(typeof(weekOffset)=='undefined')
{
	dayOffset = +0;
}
else
{
	dayOffset = weekOffset*7;
}
var nextSunday = this;
if(nextSunday.getDay()==0) {
	nextSunday.setDate(nextSunday.getDate()+dayOffset);
	return nextSunday; //it's Sunday!
}
nextSunday.setDate(nextSunday.getDate() + (7 - nextSunday.getDay()));
nextSunday.setDate(nextSunday.getDate()+dayOffset);
return nextSunday;
return false;
}

Date.prototype.getNextDay = function(dayNumber, weekOffset) {
var dayOffset = 0;
if(typeof(weekOffset)=='undefined')
{
	dayOffset = +0;
}
else
{
	dayOffset = weekOffset*7;
}
var nextSunday = this;
if(nextSunday.getDay()==dayNumber) {
	nextSunday.setDate(nextSunday.getDate()+dayOffset);
	return nextSunday; //it's Sunday!
}
nextSunday.setDate(nextSunday.getDate() + (dayNumber - nextSunday.getDay()));
nextSunday.setDate(nextSunday.getDate()+dayOffset);
return nextSunday;
return false;
}


Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay())/7);
}




/*
	Date Format 1.1
	(c) 2007 Steven Levithan <stevenlevithan.com>
	MIT license
	With code by Scott Trenda (Z and o flags, and enhanced brevity)
*/

/*** dateFormat
	Accepts a date, a mask, or a date and a mask.
	Returns a formatted version of the given date.
	The date defaults to the current date/time.
	The mask defaults ``"ddd mmm d yyyy HH:MM:ss"``.
*/
var dateFormat = function () {
	var	token        = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloZ]|"[^"]*"|'[^']*'/g,
		timezone     = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (value, length) {
			value = String(value);
			length = parseInt(length) || 2;
			while (value.length < length)
				value = "0" + value;
			return value;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask) {
		// Treat the first argument as a mask if it doesn't contain any numbers
		if (
			arguments.length == 1 &&
			(typeof date == "string" || date instanceof String) &&
			!/\d/.test(date)
		) {
			mask = date;
			date = undefined;
		}

		date = date ? new Date(date) : new Date();
		if (isNaN(date))
			throw "invalid date";

		var dF = dateFormat;
		mask   = String(dF.masks[mask] || mask || dF.masks["default"]);

		var	d = date.getDate(),
			D = date.getDay(),
			m = date.getMonth(),
			y = date.getFullYear(),
			H = date.getHours(),
			M = date.getMinutes(),
			s = date.getSeconds(),
			L = date.getMilliseconds(),
			o = date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4)
			};

		return mask.replace(token, function ($0) {
			return ($0 in flags) ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":       "ddd mmm d yyyy HH:MM:ss",
	shortDate:       "m/d/yy",
	mediumDate:      "mmm d, yyyy",
	longDate:        "mmmm d, yyyy",
	fullDate:        "dddd, mmmm d, yyyy",
	shortTime:       "h:MM TT",
	mediumTime:      "h:MM:ss TT",
	longTime:        "h:MM:ss TT Z",
	isoDate:         "yyyy-mm-dd",
	isoTime:         "HH:MM:ss",
	isoDateTime:     "yyyy-mm-dd'T'HH:MM:ss",
	isoFullDateTime: "yyyy-mm-dd'T'HH:MM:ss.lo"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask) {
	return dateFormat(this, mask);
}



function open_qxlTransfer_window(ad_car_id)
{
var url = "http://qxl.bilzonen.dk/Login.aspx?ad_car_id=" + ad_car_id;
 //popup window
 var qxlTransferWnd = window.open(url, "", "height=679,width=1044,menubar=0,resizable=1,scrollbars=1,status=1,titlebar=0,toolbar=0,left=100,top=50");
	
// if (qxlTransferWnd)
//     qxlTransferWnd.focus();
	
}
	


function open_new_window(url)
{
 //popup window
 var newWnd = window.open(url, "", "height=679,width=500,menubar=0,resizable=1,scrollbars=1,status=1,titlebar=0,toolbar=0,left=100,top=50");
	
// if (qxlTransferWnd)
//     qxlTransferWnd.focus();
	
}
	
function biloekonomiTab(url)
{
	var rand_no = Math.floor((10-8)*Math.random()) + 1;
	if (parseInt(rand_no)==2)
		window.location = url+"?tab=2&altTemplate=bilzonen.dk%20-%20BilEkonomi%20section%20-%20forsikring";
	if (parseInt(rand_no)==1)
		window.location = url;
	
}

/*** Google page group tracking  ***/
function googleTracking(arg)
{
	var pageTracker = _gat._getTracker("UA-1359246-1");	
	var gaString = arg;
	pageTracker._trackPageview(gaString);
}