var vpcomp = {};

vpcomp.itemwidth = 208;
vpcomp.maxvisibleitemcount = 3;
vpcomp.currentleft = 0;
vpcomp.slidestep = 10;
vpcomp.panleft = vpcomp.itemwidth;
vpcomp.panright = -vpcomp.itemwidth;
vpcomp.slideactive = false;
vpcomp.itemsvisible = [];
vpcomp.firstitemvisible = 1;

vpcomp.cssRules = 'cssRules';
if (document.all) vpcomp.cssRules = 'rules';

vpcomp.btnleftid = 'btnvpleft';
vpcomp.btnrightid = 'btnvpright';

vpcomp.initialise = function(id,itemcount,lcltxtSave,lcltxtSaved,bProdChanged){
	vpcomp.viewportid = id;

	// total number of items
	vpcomp.totalitemcount = itemcount;

	// set the number of active items - items that could be visible with scrolling (to start they are all but some may be unchecked manually)
	vpcomp.activeitemcount = itemcount;
	
	// set itemsvisible array to indicate the first x items are visible to start with
	for (var i=1; i<=vpcomp.totalitemcount; i++) vpcomp.itemsvisible[i]=(i<=vpcomp.maxvisibleitemcount);

	// check and if applicable restore a previous view
	vpcomp.restoreview(bProdChanged);
	vpcomp.setslidebtnstatus();
	vpcomp.resettables();
	vpcomp.resetshortlistgreyout();
	vpcomp.settechspecdiffs();
	vpcomp.aligndealerbtns();

	vpcomp.lcltxtSave = lcltxtSave;
	vpcomp.lcltxtSaved = lcltxtSaved;
	document.getElementById('hlShortlistSave').innerHTML = lcltxtSave;
}

vpcomp.getElementsByClassName = function(classname, node) {
if(!node) node = document.getElementsByTagName("body")[0];
var a = [];
var re = new RegExp('\\b' + classname + '\\b');
var els = node.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++)
if(re.test(els[i].className))a.push(els[i]);
return a;
}

//ViewPort SSS - slide left or right
vpcomp.slide = function(slidevalue){

	var ito = (vpcomp.currentleft + slidevalue);

	// Check we can slide
	if (!(vpcomp.slideactive)&&(ito >= (-((vpcomp.activeitemcount - vpcomp.maxvisibleitemcount) * vpcomp.itemwidth)) && ito <= 0)){

		document.getElementById('hlShortlistSave').innerHTML = vpcomp.lcltxtSave;

		vpcomp.slideactive = true;
		window.setTimeout('vpcomp.slideevent(' + vpcomp.currentleft + ',' + ito + ')',1);
		vpcomp.currentleft += slidevalue;
		vpcomp.setslidebtnstatus();

		// keep track on how many items we have set to visible in vpcomp.itemsvisible so we don't go over the max
		var setitemsvisiblecount = 0;

		// keep track of what is now visible and adjust table visible items appropriately
		if (slidevalue == vpcomp.panright){
			// first item can no longer be visible
			vpcomp.itemsvisible[vpcomp.firstitemvisible] = false;

			for (var i=(vpcomp.firstitemvisible+1); setitemsvisiblecount<vpcomp.maxvisibleitemcount; i++){
				if (document.getElementById('itemsel' + i).checked){
					vpcomp.itemsvisible[i] = true;
					setitemsvisiblecount += 1;
					if (setitemsvisiblecount == 1) vpcomp.firstitemvisible = i;
				}
			}
		}
		else{
			// loop back until found a checked item
			for (var i=(vpcomp.firstitemvisible-1); i>0; i--){
				if (document.getElementById('itemsel' + i).checked){
					vpcomp.itemsvisible[i] = true;
					vpcomp.firstitemvisible = i;
					setitemsvisiblecount = 1;
					break;
				}
			}
			// loop forward to set the required number of visible items
			for (var i=(vpcomp.firstitemvisible+1); i<=vpcomp.totalitemcount; i++){
				if ((document.getElementById('itemsel' + i).checked)&&(setitemsvisiblecount<vpcomp.maxvisibleitemcount)){
					vpcomp.itemsvisible[i] = true;
					setitemsvisiblecount += 1;
				}
				else vpcomp.itemsvisible[i] = false;
			}
		}
		vpcomp.resettables();
		vpcomp.resetshortlistgreyout();
		vpcomp.settechspecdiffs();
		vpcomp.aligndealerbtns();
	}
}

vpcomp.resettables = function(){
	var setitemsvisiblecount = 0;
	// hide/show relevent tds
	for (var i=1; i<=vpcomp.totalitemcount; i++){
		if (vpcomp.itemsvisible[i]){
			//show
			vpcomp.showcolcol(i);
			setitemsvisiblecount += 1;
		}
		else{
			//hide
			vpcomp.hidecolcol(i);
		}
	}

	// work out which column is the 3rd as we need to set a class to avoid the right-border background image from showing as it is a wide column and always has a right table border.
	vpcomp.fixlastableborder();

	//if visible items is less than the max we can show at once, show an appropriate number of blank columns
	for (var i=2; i<=vpcomp.maxvisibleitemcount; i++){
		if (i>setitemsvisiblecount) vpcomp.showcolblank(i);
		else vpcomp.hidecolblank(i);
	}
}

vpcomp.slideevent = function(ifrom,ito){
	var newleft;

	if (Math.abs(ifrom-ito) <= vpcomp.slidestep){
		newleft = ito;
		document.getElementById(vpcomp.viewportid).style.left = newleft + 'px';
		vpcomp.slideactive = false;
	}
	else{
		switch (true){
			case (ito < ifrom):
				newleft = (ifrom - vpcomp.slidestep);
				vpcomp.slideeventpos(newleft,ito);
				break;
			case (ito > ifrom):
				newleft = (ifrom + vpcomp.slidestep);
				vpcomp.slideeventpos(newleft,ito);
				break;
		}
	}
}
vpcomp.slideeventpos = function(newleft,ito){
	document.getElementById(vpcomp.viewportid).style.left = newleft + 'px';
	window.setTimeout('vpcomp.slideevent(' + newleft + ',' + ito + ')',1);
}

vpcomp.setslidebtnstatus = function(){

	var obtnright = document.getElementById(vpcomp.btnrightid);
	var obtnleft = document.getElementById(vpcomp.btnleftid);

	if ((vpcomp.currentleft == (-((vpcomp.activeitemcount - vpcomp.maxvisibleitemcount) * vpcomp.itemwidth)))||(vpcomp.activeitemcount<=vpcomp.maxvisibleitemcount)){
		obtnright.className='btnvpoff';
	}
	else obtnright.className='btnvpon';
	
	if (vpcomp.currentleft == 0) obtnleft.className='btnvpoff';
	else obtnleft.className='btnvpon';
}
//ViewPort EEE

vpcomp.togglecol = function(colno){

	document.getElementById('hlShortlistSave').innerHTML = vpcomp.lcltxtSave;

	var obj = document.getElementById('itemsel' + colno);

	if (obj.checked){
		// checked - if potential to be visible set it to visible then loop through from the 1st visible to check max visible is not reached
		var tempvisiblecount = 0;
		if (colno > vpcomp.firstitemvisible){
			vpcomp.itemsvisible[colno] = true;
			for (var i=vpcomp.firstitemvisible; i<=vpcomp.totalitemcount; i++){
				if (vpcomp.itemsvisible[i]){
					tempvisiblecount ++;
					if (tempvisiblecount > vpcomp.maxvisibleitemcount){
						vpcomp.itemsvisible[i] = false;
						break;	// will only be one extra
					}
				}
			}
		}
		else{
			// work out how many items are visible as if under the limit we will try find another candidate
			for (var i=1; i<=vpcomp.totalitemcount; i++) if (vpcomp.itemsvisible[i]) tempvisiblecount ++;
		}

		// another item is active
		vpcomp.activeitemcount +=1;

		// if number of visible items is less than what we can display (they have added back an item when less then the max were showing) then find one to show
		// first by looking after the one just made visible, then by looking earlier.
		if (tempvisiblecount < vpcomp.maxvisibleitemcount) vpcomp.findnewvisiblecandidate(colno);
		
		// Enable any disabled checkboxes as there will be more than one checked now & show all hide links
		for (var i=1; i<=vpcomp.totalitemcount; i++) if (document.getElementById('itemsel' + i).disabled){
			document.getElementById('itemsel' + i).disabled=false;
			document.getElementById('vphide' + i).style.visibility='visible';
			break;
		}
	}
	else{
		//unchecked - if it was visible we need to try find another to find its place
		if (vpcomp.itemsvisible[colno]){

			// it was visible so it can't be now
			vpcomp.itemsvisible[colno] = false;

			// look for another item to make visible
			vpcomp.findnewvisiblecandidate(colno);

			// Disable checkbox & hide link if it's the last item visible
			var icountvisible = 0;
			var itempid;
			for (var i=1; i<=vpcomp.totalitemcount; i++) if (vpcomp.itemsvisible[i]){
				icountvisible++;
				itempid = i;
			}
			if (icountvisible == 1){
				document.getElementById('itemsel' + itempid).disabled=true;
				document.getElementById('vphide' + itempid).style.visibility='hidden';
			}
		}

		// another item is inactive
		vpcomp.activeitemcount -=1;
	}

	// reset slider
	vpcomp.resetslider();

	// set slide button status left/right
	vpcomp.setslidebtnstatus();

	// reset table cols
	vpcomp.resettables();
	
	// grey out/show shortlist item
	vpcomp.resetshortlistgreyout();

	// reset techspec differences
	vpcomp.settechspecdiffs();

	vpcomp.aligndealerbtns();
}

vpcomp.resetslider = function(){

	// set visibility of slider items according to checkboxes
	for (var i=1; i<=vpcomp.totalitemcount; i++){
		if (document.getElementById('itemsel' + i).checked) vpcomp.showcol('vp' + i);
		else vpcomp.hidecol('vp' + i);
	}

	// set slider positon accordingly - first find the sequence no of the first visible item within the active items only
	var tempseqno = 0;
	for (var i=1; i<=vpcomp.firstitemvisible; i++) if (document.getElementById('itemsel' + i).checked) tempseqno ++;

	vpcomp.currentleft = -((tempseqno-1) * vpcomp.itemwidth)
	document.getElementById(vpcomp.viewportid).style.left = vpcomp.currentleft + 'px';
}

vpcomp.findnewvisiblecandidate = function(startcolno){

	// variable to use for a new visible item id
	var inewvisiblecandidate = 0;

	// see if there's a candidate higher to become visible to take its place - include the current item as if adding it might become visible
	for (var i=(startcolno); i<=vpcomp.totalitemcount; i++){
		if ((document.getElementById('itemsel' + i).checked)&&(!vpcomp.itemsvisible[i])){
			inewvisiblecandidate = i;
			break;
		}
	}

	// if not found, look lower instead
	if (inewvisiblecandidate==0){
		for (var i=(startcolno-1); i>0; i--){
			if ((document.getElementById('itemsel' + i).checked)&&(!vpcomp.itemsvisible[i])){
				inewvisiblecandidate = i;
				break;
			}
		}
	}

	// Recalculate the first visible candidate as it may have changed
	vpcomp.itemsvisible[inewvisiblecandidate] = true;
	
	// reset first visible item as it may have changed
	for (var i=1; i<=vpcomp.totalitemcount; i++){
		if (vpcomp.itemsvisible[i]){
			vpcomp.firstitemvisible = i;
			break;
		}
	}
}

vpcomp.hidecol = function(classname){
	var a = vpcomp.getElementsByClassName(classname);
	for(var i=0;i<a.length;i++) a[i].style.display='none';
}
vpcomp.showcol = function(classname){
	var a = vpcomp.getElementsByClassName(classname);
	for(var i=0;i<a.length;i++) a[i].style.display='';
}

vpcomp.setOpacity = function(obj, opacity) {
  opacity = (opacity == 100)?99.999:opacity;
  // IE/Win
  obj.style.filter = "alpha(opacity:"+opacity+")";
  // Safari<1.2, Konqueror
  obj.style.KHTMLOpacity = opacity/100;
  // Older Mozilla and Firefox
  obj.style.MozOpacity = opacity/100;
  // Safari 1.2, newer Firefox and Mozilla, CSS3
  obj.style.opacity = opacity/100;
}

// show or greyout shortlist image & text
vpcomp.resetshortlistgreyout = function(){
	var bChecked
	for (var i=1; i<=vpcomp.totalitemcount; i++){
		bChecked = document.getElementById('itemsel' + i).checked
		vpcomp.setOpacity(document.getElementById('itemselthumb' + i),(bChecked)?100:30);
		document.getElementById('itemseltxt' + i).className = (bChecked)?'':'disabled';
		
		// show/hide arrow for visible items
		document.getElementById('itemselind' + i).style.display = (vpcomp.itemsvisible[i])?'':'none';
	}
}

// Uncheck item and toggle to hide
vpcomp.togglecolhide = function(colno){
	document.getElementById('itemsel' + colno).checked = false;
	vpcomp.togglecol(colno);
}

// Save settings to cookie
vpcomp.save = function(){
	vpcomp.Set_Cookie('pcNo',vpcomp.totalitemcount,30,'/','','');
	vpcomp.Set_Cookie('pcNoActive',vpcomp.activeitemcount,30,'/','','');
	vpcomp.Set_Cookie('pcFirstVisible',vpcomp.firstitemvisible,30,'/','','');
	vpcomp.Set_Cookie('pcCurrentLeft',vpcomp.currentleft,30,'/','','');

	for (var i=1; i<=vpcomp.totalitemcount; i++){
		vpcomp.Set_Cookie('pcItem' + i + 'Code',document.getElementById('itemseltxt' + i).innerHTML,30,'/','','');
		vpcomp.Set_Cookie('pcItem' + i + 'Checked',document.getElementById('itemsel' + i).checked,30,'/','','');
		vpcomp.Set_Cookie('pcItem' + i + 'Visible',vpcomp.itemsvisible[i],30,'/','','');
	}
	document.getElementById('hlShortlistSave').innerHTML = vpcomp.lcltxtSaved;
}

// Restore settings from cookie
vpcomp.restoreview = function(bProdChanged){
	var bSameItems = true;

	if (bProdChanged)document.getElementById('divProductsChanged').style.display='block';

	// check data is the same as in cookie - 1st that cookie is defined
	var vpcompNo = vpcomp.Get_Cookie('pcNo');
	if (vpcompNo != null){
		// if products changed we ned to show message and delete cookie
		if (bProdChanged){
			vpcomp.Delete_Cookie('pcNo','/','');
			vpcomp.Delete_Cookie('pcNoActive','/','');
			vpcomp.Delete_Cookie('pcFirstVisible','/','');
			vpcomp.Delete_Cookie('pcCurrentLeft','/','');
			for (var i=1; i<=vpcomp.totalitemcount; i++) vpcomp.Delete_Cookie('pcItem' + i + 'Visible','/','');
		}
		else{
			// cookie must have same number of items
			if (vpcompNo == vpcomp.totalitemcount){

				// cookie must have same product codes
				for (var i=1; i<=vpcomp.totalitemcount; i++){
					if (document.getElementById('itemseltxt' + i).innerHTML != vpcomp.Get_Cookie('pcItem' + i + 'Code')){
						bSameItems = false;
						break;
					}
				}

				// If the same we need to setup required view
				if (bSameItems){
					vpcomp.activeitemcount = parseInt(vpcomp.Get_Cookie('pcNoActive'));

					vpcomp.firstitemvisible = parseInt(vpcomp.Get_Cookie('pcFirstVisible'));
					vpcomp.currentleft = parseInt(vpcomp.Get_Cookie('pcCurrentLeft'));

					for (var i=1; i<=vpcomp.totalitemcount; i++){
						document.getElementById('itemsel' + i).checked = (vpcomp.Get_Cookie('pcItem' + i + 'Checked')=='true')?true:false;
						vpcomp.itemsvisible[i] = (vpcomp.Get_Cookie('pcItem' + i + 'Visible')=='true')?true:false;
					}

					vpcomp.resetslider();
				}
			}
		}
	}
}


vpcomp.Delete_Cookie = function(name,path,domain){
	if (vpcomp.Get_Cookie(name)) document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

vpcomp.Set_Cookie = function(name, value, expires, path, domain, secure){
	// set time, in milliseconds
	var today = new Date();
	today.setTime(today.getTime());

	// If the expires variable is set, make the correct expires time (days)
	if (expires) expires = expires * 1000 * 60 * 60 * 24;

	var expires_date = new Date(today.getTime() + (expires));

	document.cookie = name + "=" +escape(value) +
	((expires) ? ";expires=" + expires_date.toGMTString() : "") + 
	((path) ? ";path=" + path : "") + 
	((domain) ? ";domain=" + domain : "") +
	((secure) ? ";secure" : "");
}

vpcomp.Get_Cookie = function(check_name){
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split(';');
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for (i = 0; i < a_all_cookies.length; i++){
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split('=');
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if (cookie_name == check_name){
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if (a_temp_cookie.length > 1){
				cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if (!b_cookie_found) return null;
}

// work out which column is the 3rd as we need to set a class to avoid the right-border background image from showing as it is a wide column and always has a right table border.
vpcomp.fixlastableborder = function(){
	var visiblecount = 0;
	var lastvisible = 0;
	for (var i=1; i<=vpcomp.totalitemcount; i++){
		if (vpcomp.itemsvisible[i]){
			lastvisible = i;
			visiblecount += 1;
		}
		// Reset border class
		var a = vpcomp.getElementsByClassName('col' + i);
		for(var ii=0;ii<a.length;ii++){
			a[ii].className = a[ii].className.replace(' nobdr','');
		}
	}
	if (visiblecount==vpcomp.maxvisibleitemcount){
		var a = vpcomp.getElementsByClassName('col' + lastvisible);
		for(var i=0;i<a.length;i++){
			a[i].className += ' nobdr';
		}
	}
}

// View the overview table & set appropriate tabs
vpcomp.viewoverview = function(){
	document.getElementById('tbloverview').style.display='';document.getElementById('tblProductComparison').style.display='none';

	document.getElementById('cntTabs-1Row-td1').className = 'firston';
	document.getElementById('cntTabs-1Row-td2').className = 'selected';
	document.getElementById('cntTabs-1Row-td3').className = 'onoff';
	document.getElementById('cntTabs-1Row-td4').className = '';
	document.getElementById('cntTabs-1Row-td5').className = 'offlast';
	
	vpcomp.aligndealerbtns();
}

// View the tech spec table & set appropriate tabs
vpcomp.viewtechspec = function(){
	document.getElementById('tblProductComparison').style.display='';document.getElementById('tbloverview').style.display='none';

	document.getElementById('cntTabs-1Row-td1').className = 'firstoff';
	document.getElementById('cntTabs-1Row-td2').className = '';
	document.getElementById('cntTabs-1Row-td3').className = 'offon';
	document.getElementById('cntTabs-1Row-td4').className = 'selected';
	document.getElementById('cntTabs-1Row-td5').className = 'onlast';
}

// Highlight techspec rows that have different specs for visible products
vpcomp.settechspecdiffs = function(){
/*
	var bDiff;
	var sStore;
	var a = vpcomp.getElementsByClassName('rtsir');
	for(var i=0;i<a.length;i++){
		// reset
		a[i].className = a[i].className.replace(' diff','');
		bDiff = false;
		sStore = '';

		// compare visible techspecs - loop through visible items
		for (var ii=1; ii<=vpcomp.totalitemcount; ii++){
			if (vpcomp.itemsvisible[ii]){
				// get techspec for this
				var b = vpcomp.getElementsByClassName('col' + ii, a[i]);
				// see if different
				if (sStore != ''){
					if (sStore != b[0].innerHTML){
						bDiff = true;
						break;
					}
				}
				else sStore = b[0].innerHTML;
			}
		}

		// if different, then highlight
		if (bDiff) a[i].className += ' diff';
	}
	*/
}

vpcomp.hidecolcol = function(i){document.styleSheets[0][vpcomp.cssRules][i-1].style['display'] = 'none';}
vpcomp.showcolcol = function(i){document.styleSheets[0][vpcomp.cssRules][i-1].style['display'] = '';}
vpcomp.hidecolblank = function(i){document.styleSheets[0][vpcomp.cssRules][i+3].style['display'] = 'none';}
vpcomp.showcolblank = function(i){document.styleSheets[0][vpcomp.cssRules][i+3].style['display'] = '';}

// Align dealer locator buttons by adding extra top margin
vpcomp.aligndealerbtns = function(){

	var objVisible = new Array();
	var objCount = 0;
	var objHighest = 0;

	// reset top margin on all dealer locator buttons to 7px
	var a = vpcomp.getElementsByClassName('cntDealerLocatorTop');
	for(var i=0;i<a.length;i++){
		a[i].style.marginTop = '7px';

		// if visible, store object
		if (vpcomp.itemsvisible[a[i].parentNode.parentNode.parentNode.parentNode.className.charAt(3)]){
			objCount +=1;
			objVisible[objCount] = a[i];
			
			// store highest
			if (a[i].offsetTop > objHighest) objHighest = a[i].offsetTop;
		}
	}

	// set all to same height with extra margin
	for (var i=1;i<=objCount;i++){
		objVisible[i].style.marginTop = ((objHighest - objVisible[i].offsetTop) + 7) + 'px';
	}

}