/*--- Common functions which are called on every page -------------------------------------------------*/

function AHInit(){
    AHButtons();
    //next 2 lines disabled by Chris - needs YAHOO.AutoHub.Util to function - re-enable on live server 
    //document.getElementById('logInLink').onclick = function(){showLogin('Log In to your account'); return false;};
    //document.getElementById('signUpLink').onclick = function(){showLogin('Sign up for your free account'); return false;};
}

/*--- Image preloading --------------------------------------------------------------------------------*/

var imagePath = "/media/FWRK/images/";

/* TODO: Go through all used images, and update this list */
var searchSet = new Array();
searchSet[0] = "body_style_multi.gif";
searchSet[1] = "colours_multi.gif";
var resultSet = new Array();
resultSet[0] = "bg_left_col_960w.gif";
resultSet[1] = "striped_bg.gif";
resultSet[2] = "action_icons_multi_2.gif";
resultSet[3] = "sort_arrows_multi.gif";
resultSet[4] = "new_res_top.gif";
resultSet[5] = "new_res_bg.gif";
resultSet[6] = "100px_grad_up_white.png";
resultSet[7] = "100px_grad_up_white.gif";
resultSet[8] = "stc_multi.gif";
resultSet[9] = "new_res_div.gif";
var detailSet = new Array();
detailSet[0] = "bg_left_col_960w.gif";
detailSet[1] = "striped_bg.gif";
detailSet[2] = "required.gif";
detailSet[3] = "gallery_icons_multi.gif";
detailSet[4] = "action_icons_multi_2.gif";


//other image sets to add!
function preload(set){
    if(document.images){
        var images = new Array();
        for(i=0; i<set.length; i++){
            images[i] = new Image();
            images[i].src = imagePath+set[i];
        }
        return (images);
    }
}

/*--- Forms -------------------------------------------------------------------------------------------*/

limitText = function(el, disp, maxChars){
//this function limits number of chars entered in a textarea and updates a span etc with remaining chars message
//call with onkeyup event -eg limitText(element id, char count span id, max permitted chars)
    var target = document.getElementById(el);
    var count = maxChars-target.value.length;
    if(count<=0){
        trimmed = target.value.substring(0, maxChars);
        target.value = trimmed;
        count=0;
    }
    var track = document.getElementById(disp);
    track.innerHTML = '('+count+' of '+maxChars+' characters remaining)';
}

/*--- Button replacement ------------------------------------------------------------------------------*/

function AHButtons(){
//this function replaces all standard html submit buttons and text links with the class 'but' with nicer looking buttons, which are actually css styled links
//Users without JS will see a default styled button/link.
    //add extra markup to innerHTML of links
    var bl = document.getElementsByTagName("A");
    bllist = [];
    for(i=0; i<bl.length; i++){
        if(bl[i].className.search(/but/)>=0){
            bllist.push(bl[i]);
        }
    }
    for(i=0; i<bllist.length; i++){
        var label = bllist[i].innerHTML;
        //modify className - switch 'but' to 'AHBut'
        bllist[i].className = bllist[i].className.replace('but','AHBut');
        bllist[i].innerHTML = "<del><div class='but_outer'><div class='but_inner'><div class='but_bg'>&nbsp;</div><div class=but_label>"+label+"</div></div></div></del>";
        bllist[i].style.visibility = "inherit";//text link was originally hidden with css to stop ugly flash
    }
    //replace html submit buttons, modify 'but' class name to 'AHBut', set onclick to submit parent form
    var sb = document.getElementsByTagName("INPUT");
    sblist = [];
    for(i=0; i<sb.length; i++){
        var t = sb[i].getAttribute("type");
        if(t=="submit"){
            sblist.push(sb[i]);
        }
    }
    //loop through submit buttons, replace with styled links
    for(i=0; i<sblist.length; i++){
        var target = sblist[i];
        var fragment = document.createDocumentFragment();
        newLink = document.createElement("A");
        newLink.id = sblist[i].id;//copy id to new link
        newLink.href = "#";
        newLink.title = sblist[i].value;//make title same as button text
        newLink.className = sblist[i].className.replace('but','AHBut');//copy class across, change 'but' to 'AHBut'
        var t = sblist[i].getAttribute("type");
		if(t=="submit"){
			newLink.onclick = function(){submitForm(this.id,'submit'); return false;};
		}else if(t=="reset"){
			newLink.onclick = function(){submitForm(this.id,'reset'); return false;};
		}
		//if button has an onclick event specified, copy to new link
		var preserveOCE = sblist[i].getAttribute("onclick");
		if(preserveOCE !== null){
			newLink.setAttribute("onclick", preserveOCE);
		}
		newLink.innerHTML = "<del><div class='but_outer'><div class='but_inner'><div class='but_bg'>&nbsp;</div><div class='but_label'>"+sblist[i].value+"</div></div></div></del>";
        newLink.style.visibility="inherit";//originals were hidden with css
        fragment.appendChild(newLink);
        target.parentNode.replaceChild(fragment, target);
    }
}
//submits the form that any specified element (usually a button) is inside.
function submitForm(child){
    var el = document.getElementById(child);
    var error=0;
    var i=0;
    while(el && el.tagName!="FORM"){
        if(i>=100 || el.tagName=="BODY"){//breaks loop if body tag found, or 100 loops are performed
            error++;
            break;
        }
        el=el.parentNode;//jump up one level
        i++;
    }
    if(error==0 && el){
        el.submit();//no problems, submit form
    }
}

/*--- pop up tips -  THIS HAS BEEN REPLACED -------------------------------------------------------------------------------------*/

function loadTips(){
        new Tip('tip_searchArea', 'Lorum ipsum Dolor sit amet', {
                        title: 'Search Within:',
                        radius: 0,
                        border: 1,
                        borderColor: '#C7C7C7',
                        style: 'default',
                        stem: 'leftTop',
                        hook: { tip: 'leftTop', mouse: true },
                        offset: { x: 14, y: 14 }
        });
        new Tip('tip_vendors', 'Lorum ipsum Dolor sit amet', {
                        title: 'Vendors:',
                        radius: 0,
                        border: 1,
                        borderColor: '#C7C7C7',
                        style: 'default',
                        stem: 'leftTop',
                        hook: { tip: 'leftTop', mouse: true },
                        offset: { x: 14, y: 14 }
        });
        new Tip('tip_featured', 'Lorum ipsum Dolor sit amet', {
                        title: 'Featured:',
                        radius: 0,
                        border: 1,
                        borderColor: '#C7C7C7',
                        style: 'default',
                        stem: 'leftTop',
                        hook: { tip: 'leftTop', mouse: true },
                        offset: { x: 14, y: 14 }
        });
        new Tip('tip_premium', 'Lorum ipsum Dolor sit amet', {
                        title: 'Premium:',
                        radius: 0,
                        border: 1,
                        borderColor: '#C7C7C7',
                        style: 'default',
                        stem: 'leftTop',
                        hook: { tip: 'leftTop', mouse: true },
                        offset: { x: 14, y: 14 }
        });
        new Tip('tip_standard', 'Lorum ipsum Dolor sit amet', {
                        title: 'Standard:',
                        radius: 0,
                        border: 1,
                        borderColor: '#C7C7C7',
                        style: 'default',
                        stem: 'leftTop',
                        hook: { tip: 'leftTop', mouse: true },
                        offset: { x: 14, y: 14 }
        });
        new Tip('tip_compare', 'Lorum ipsum Dolor sit amet', {
                        title: 'Compare:',
                        radius: 0,
                        border: 1,
                        borderColor: '#C7C7C7',
                        style: 'default',
                        stem: 'leftTop',
                        hook: { tip: 'leftTop', mouse: true },
                        offset: { x: 14, y: 14 }
        });
}

/*--- log in scripts -------------------------------------------------------------------------------------*/

function submitOnEnter(e, formId, bUseAjax){
	var keycode;
	if (window.event){
		keycode = window.event.keyCode;
	}else{
		if (e){
			keycode = e.which;
		}else{
			return true;
		}
	}
	if (keycode == 13){
		var f = document.getElementById(formId);
		if( f )
		{
			// In AJAX mode use the AutoHub JS submit
			if( bUseAjax )
				YAHOO.AutoHub.Login.Submit(f);
			else // else its a normal form submit
				f.submit();
		}
	}
}


function validateEmail(e){  
    var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    if(pattern.test(e)){         
        return true;   
    }else{   
        return false; 
    }
}
function checkEmail(){
    var e = document.forms["signUpForm"].email.value;
    if(validateEmail(e)){
        document.forms["signUpForm"].email.className="matched";
        return true;
    }else{
        document.forms["signUpForm"].email.className="notMatched";
        return false;
    }
}
// RALUCA: added text parameters t allow translation in the calling page
function step2Prog(sCompletedText, sFinishText){
    var percent = 40; //starting percentage
    if(document.forms["signUpForm"].name.value!=""){
        percent +=20;   
    }
    if(document.forms["signUpForm"].nickname.value!=""){
        percent +=20;   
    }
    if(document.forms["signUpForm"].gender[0].checked || document.forms["signUpForm"].gender[1].checked){
        percent +=20;   
    }
    document.getElementById("progBar").className="p"+percent;
    if(percent==100){
        //var text="Complete! Please click 'Finish'";
        var text = sFinishText;
    }else{
        //var text=percent+"% Completed"; 
        var text = percent+"% "+sCompletedText;
    }
    document.getElementById("progText").innerHTML=text;
}
/* [CS] - not currently used - remove?
function createNick(){
       var email = document.forms["signUpForm"].email.value;
       var nick = email.split(/[@]/);
       if(nick.length>1){
               document.forms["signUpForm"].nickname.value=nick[0];
       }
}
*/
function checkPasswordMatch(){
        var pass1 = document.forms["signUpForm"].pass1.value;
        var pass2 = document.forms["signUpForm"].pass2.value;
        if(pass1 && pass2){
                if(pass1 === pass2){
                        document.forms["signUpForm"].pass2.className="matched";
                        return true;
                }else{
                        document.forms["signUpForm"].pass2.className="notMatched";
                        return false;
                }
        }else{
                document.forms["signUpForm"].pass2.className="";
                return false;
        }
}
function showLogin(message, mode){
				//mode should be either 'login' or 'join' and is used to hilight a particular area of the login/join popup
        if(message){
                var message = message;
        }else{
                var message="Account Log In";   
        }
        document.getElementById("logInTitle").innerHTML=YAHOO.AutoHub.Util.XhtmlEncode(message);
        document.getElementById("loginPopup").style.display="block";       
        document.getElementById("loginMask").style.display="block";
				window.scroll(0,0);
				if(mode){
					if(mode=='join'){
						document.getElementById("newUsers").className='active';
					}else if(mode=='login'){
						document.getElementById("existingUsers").className='active';
					}
				}
        hideSelects();
}
var znLoginErrorCount = 0;
function reportLoginError(message){
        // You can report this error however you want.  For now I'm just replacing the
        // "Existing users: please login to your account" text with an error.
        znLoginErrorCount ++ ;
        html = "<h3>Error"+(znLoginErrorCount>1?'('+znLoginErrorCount+')':0)+": <span>"+YAHOO.AutoHub.Util.XhtmlEncode(message)+"</span></h3>" ;
        // Presumably if znLoginErrorCount >= 3 or something, we display a "forgot password?" link,
        // but that's not currently implemented.
        document.getElementById('iLoginStatusText').innerHTML = html;
}
function hideLogin(){
        var defaultMsg = "Account Log In";
        document.getElementById("logInTitle").innerHTML=defaultMsg;
        document.getElementById("loginPopup").style.display="none";        
        document.getElementById("loginMask").style.display="none";
				document.getElementById("newUsers").className='';
				document.getElementById("existingUsers").className='';
        showSelects();
}
function hideSelects(){//hides select dropdowns (IE6 places these above page mask - ignores z-index) 
        selects = document.getElementsByTagName("SELECT");
        for(i=0; i<selects.length; i++){
            selects[i].style.visibility="hidden";   
        }
}
function showSelects(){
        selects = document.getElementsByTagName("SELECT");
        for(i=0; i<selects.length; i++){
            selects[i].style.visibility="visible";  
        }
}
/*--- vehicle search page -------------------------------------------------------------------------------------*/

// RALUCA: added show / hide link text to allow translation (by the calling script)
function initExtra(sShowLink, sHideLink){
        d = "block";/*yes, this is right - it's switched by toggleExtra function*/
        toggleExtra(sShowLink, sHideLink);
        //set visibility of toggle link parent li (hidden by css)
        document.getElementById("showExtra").style.display="block";
}
// RALUCA: added show / hide link text to allow translation (by the calling script)
function toggleExtra(sShowLink, sHideLink){
		//switch visibility var
        if(d=="none"){d="block";}else{d="none"}
        //scan document for Li's with a class of 'extra'
        items = document.getElementsByTagName("LI");
        extraList = [];
        for(i=0; i<items.length; i++){
                if(items[i].className.search(/extra/)>=0){
                        extraList.push(items[i]);       
                }
        }
        //loop through extra criteria, set display type
        for(i=0; i<extraList.length; i++){
                extraList[i].style.display=d;
        }
        //update toggle link content
        //switch link text
        //if(d=="block"){linkText="[ - ] hide more search criteria";}else{linkText="[ + ] show more search criteria";}
        if(d=="block"){linkText="[ - ] "+sHideLink;}else{linkText="[ + ] "+sShowLink;}
        document.getElementById("showExtra").innerHTML=linkText;
}
function toggleBodyStyles(d){
        document.getElementById("bodyStyles").style.display=d;
}

function updateSwatch(el){
    //get the selected value
    var colourSelect = document.getElementById(el);
    // RALUCA: color value matches numeric ID from the DB; css doesn't seem to like numeric values so prefixed by 'c'
    var colour = "chip"+colourSelect.options[colourSelect.selectedIndex].value;
    //alert(colour);
    document.getElementById(el+"sample").className=colour;
}

/*--- Vehicle results page -------------------------------------------------------------------------------------*/

function switchClass(target,newClass){
                document.getElementById(target).className=newClass;
}
function colorResults(pc,fc,sc){
    //sets border color of search results (premium, featured, standard etc) - stops ugly flash whilst loading
    //border colour is actually background colour of result wrapper div - masked by semi-transparent gifs
    items = document.getElementsByTagName("DIV");
        premium = [];
        featured = [];
        standard = [];
        for(i=0; i<items.length; i++){
                if(items[i].className.search(/premium/)>=0){
                        premium.push(items[i]);       
                }else if(items[i].className.search(/featured/)>=0){
                        featured.push(items[i]);                                   
                }else if(items[i].className.search(/standard/)>=0){
                        standard.push(items[i]);                                   
                }
        }
        //loop through premium results, set border colour
        for(i=0; i<premium.length; i++){
                premium[i].style.backgroundColor=pc;
        }
        //loop through featured results, set border colour
        for(i=0; i<featured.length; i++){
                featured[i].style.backgroundColor=fc;
        }
        //loop through standard results, set border colour
        for(i=0; i<standard.length; i++){
                standard[i].style.backgroundColor=sc;
        }
}

function positionStickies(){
	window.winH = getHeight();
	window.winS = getScrollY();
	//top sort bar
	if(document.getElementById('sortBarTop')){
		var sortY = document.getElementById("sortBarPos").offsetTop;
		var sortEl = document.getElementById('sortBarTop');
		if(winS >= sortY){
			sortEl.style.position = 'fixed';
			sortEl.style.top = '0'
		}else{
			sortEl.style.position = '';
			sortEl.style.top = '';
		}
	}
	//ad category bars
	if(document.getElementById("resPrem")){
		var prmY = document.getElementById("resPrem").parentNode.offsetTop;
	}
	if(document.getElementById("resFeat")){
		var featY = document.getElementById("resFeat").parentNode.offsetTop;
	}
	if(document.getElementById("resStd")){
		var stdY = document.getElementById("resStd").parentNode.offsetTop;
	}
	if(prmY || featY || stdY){
		var fix = ''
		if(prmY && winS+21>=prmY){
			fix='p';
		}
		if(featY && winS+21>=featY){
			fix='f';
		}
		if(stdY && winS+21>=stdY){
			fix='s';
		}
		var stick = function(id){
			if(el=document.getElementById(id)){
				el.style.position='fixed';
				el.style.top='1.4166em';
				el.style.left=getElementPosition('rw').left+"px";
			}
		}
		var release = function(id){
			if(el=document.getElementById(id)){
				el.style.position='';
				el.style.top='';
				el.style.left='';
			}
		}
		switch(fix){
		case 'p':stick('resPrem');release('resFeat');release('resStd');break;
		case 'f':release('resPrem');stick('resFeat');release('resStd');break;
		case 's':release('resPrem');release('resFeat');stick('resStd');break;
		default:release('resPrem');release('resFeat');release('resStd');
		}
	}
	//bottom bar
	if(document.getElementById('stickyBar')){
		var footEl = document.getElementById('pageFooter');
		var barEl = document.getElementById('stickyBar');
		var footH = footEl.offsetHeight;
		var footY = footEl.offsetTop;
		var barH = barEl.offsetHeight;
		if(footY>(winH+winS)){
			var stickyPos = 0;
		}else{
			var stickyPos = winH-(footY-winS);
		}
		document.getElementById('stickyBar').style.bottom = stickyPos + "px";
	}
	//if(getBrowser()!='ie6'){//ie6 does not support position:fixed TODO: fix this - it's not working for IE7
		window.onload = function(){positionStickies();};
		window.onscroll = function(){positionStickies();};
		window.onresize = function(){positionStickies();};
	//}
}



/*--- Vehicle detail page -------------------------------------------------------------------------------------*/

/*gallery script*/
function initGallery(){
        //alert("init Gallery");
        slideshowRunning=false;
        thumbPage=1;
        images = document.getElementsByTagName("IMG");
        thumbList = [];
        for(i=0; i<images.length; i++){
                if(images[i].className=="galleryThumb"){
                        thumbList.push(images[i]);      
                }
        }
        //if there are vehicle images on the page, show gallery
        if(thumbList.length>0){
                //split thumbs into groups(pages) of 9 images
                thumbPages = "";
                pages = [];
                for(i=0; i<thumbList.length; i++){
                        //which page are we adding to?
                        page = Math.ceil((i+1)/9);
                        if(pages[page]==null){pages[page]="";}
                        pages[page]+="<li><a id='p"+i+"' href='#' onclick='changePic("+i+"); return false'><img src='"+thumbList[i].src+"' alt='Photo "+(i+1)+" of "+thumbList.length+"' /></a></li>";
                }
                //loop through pages, wrap each in a UL with page id
                for(i=1; i<pages.length; i++){
                        thumbPages += "<ul class='thumbs' id='page"+i+"'>"+pages[i]+"</ul>";    
                }
                //generate gallery HTML code
                //grab the vehicle make, model, price from the vehicleSummaryInfo div
				var mmp = document.getElementById("vehicleSummaryInfo").innerHTML;
				galleryHTML = "<div id='gallery' class='framed760'><div class='r1'></div><div class='r2'><div id='bigPicFrame'><div id='bigPicWrapper'><img id='bigPic' src='' alt='' /></div><div id='vehicleSummary'>"+mmp+"</div><span id='galleryNav'></span></div><div class='vDiv'>&nbsp;</div><div id='thumbWrapper'><div id='thumbScroller'><div id='thumbPageWrapper'>";
                galleryHTML += thumbPages;
				galleryHTML += "</div></div>";
				//grab enlarge pics code from viewFullSize div
				var enlargeLink = document.getElementById("postGallery").innerHTML;
				galleryHTML += "<div id='fullSizePics'>"+enlargeLink+"</div>";
				galleryHTML += "<span id='thumbPagination'></span></div></div><div class='footL'></div><div class='footR'></div></div>";
                //write gallery html to page
                gWrap = document.getElementById("galleryWrapper");
                //alert(galleryHTML);
				gWrap.innerHTML = galleryHTML;
				//hide the postGallery area (only used for simple gallery)
				document.getElementById("postGallery").style.display="none";
                //show the gallery (initially hidden by CSS
                document.getElementById("galleryWrapper").style.display="block";
                //update display
                changePic(0);
        }
}

function switchPic(thumbSrc, imageId)
{
    // RALUCA: set actual params for launchFullSize function; carId must be defined in the html page
    //document.getElementById("bigPicWrapper").innerHTML="<img id='bigPic' src='"+newSrc+"' alt='' title='Click to Enlarge' onclick='launchFullSize(\"carIdHere\",\""+imageId+"\")' />";
		var newSrc = thumbSrc.replace("104x78","640x480");
		document.getElementById("bigPicWrapper").innerHTML="<img id='bigPic' src='"+newSrc+"' alt='' title='Click to Enlarge' onclick='launchFullSize(\""+carId+"\",\""+imageId+"\")' />";
}

function changePic(imageToShow){
        if(imageToShow == null){
                imageToShow = current;
        }
        //previous image
        var prev = imageToShow-1;
        if(prev<0){prev=(thumbList.length-1);}
        //next image
        var next = imageToShow+1;
        if(next>(thumbList.length-1)){next=0;}
        var nav=document.getElementById("galleryNav");
        //disable pic switch buttons and slideshow if only 1 pic
        if(thumbList.length<2){
                switchPicStatus="disabled";
                slideshowStatus="disabled";
        }else{
                switchPicStatus="";
        }
        //set mode/appearance of slideshow button
        if(slideshowRunning==true){
                mode="stop";
                slideshowStatus="running";
                ssTitle="Pause slide show";
        }else{
                mode="start";
                slideshowStatus="stopped";
                ssTitle="Start slide show";
        }
        
        //original(with slideshow)
        //nav.innerHTML="<a id='prevPic' class='"+switchPicStatus+"' href='#' onclick='slideshow(\"stop\"); changePic("+prev+"); return false' title='Previous'></a><div>image "+(imageToShow+1)+" of "+thumbList.length+"</div><a id='nextPic' class='"+switchPicStatus+"' href='#' onclick='slideshow(\"stop\"); changePic("+next+"); return false' title='Next'></a> <a id='slideshow' class='"+slideshowStatus+"' href='#' onclick='slideshow(\""+mode+"\"); return false' title='"+ssTitle+"'></a>";
        
        //revised(no slideshow)
        nav.innerHTML="<a id='prevPic' class='"+switchPicStatus+"' href='#' onclick='slideshow(\"stop\"); changePic("+prev+"); return false' title='Previous'></a><div>Photo "+(imageToShow+1)+" of "+thumbList.length+"</div><a id='nextPic' class='"+switchPicStatus+"' href='#' onclick='slideshow(\"stop\"); changePic("+next+"); return false' title='Next'></a>";
        
        //switch pic to new image if specified
        if(imageToShow !=null){
                switchPic(thumbList[imageToShow].src,"p"+imageToShow);
                //reset styles for all thumbs
                for(i=0;i<thumbList.length;i++){
                        inactive = "p"+i;
                        document.getElementById(inactive).className="inactive";
                }
                //set class of active thumb
                active = "p"+imageToShow;
                document.getElementById(active).className="active";
                current = imageToShow;
        }
        //focus image in thumbs pane
        scrollToThumbPage();
        return true;
}
function slideshow(action){
        if(action=="start"){
                autoAdvance = setInterval(advance(),5000);
                slideshowRunning=true;
                changePic();
        }else if (action=="stop"){
                if(slideshowRunning==true){
                        clearInterval(autoAdvance);
                        slideshowRunning=false;
                        changePic();
                }
        }
}
function advance(){
        //what's the next image
        var next = current+1;
        if(next>(thumbList.length-1)){
                next=0;
        }
        changePic(next);
        return true;
}
function scrollToThumbPage(pageToFocus){
        //if page isn't specified, focus on current images page
        if(pageToFocus == null){
                //which page is the current image on?
                page = Math.floor((current)/9)+1;
                if(page<1){page=1;}
                target = page;
        }else{
                //if page is specified, scroll there
                target = pageToFocus;
                //update page tracker
                thumbPage = pageToFocus;
        }
        //scroll
        $('div#thumbScroller').scrollTo('#page'+target, 500, {axis:'x'});
        //update thumb page tracker
        thumbPage = target;
        //update thumb pagination
        //how many pages are there?
        pages = Math.ceil(thumbList.length/9);
        if(pages<1){
                pages=1;
        }
        var thumbPG = document.getElementById("thumbPagination");
        //prev page
        var prev = thumbPage-1;
        if(prev<1){
                prev=1;
                //disable prev button
                prevPageStatus="disabled";
        }else{
                prevPageStatus="";      
        }
        //next page
        var next = thumbPage+1;
        if(next>pages){
                next=pages;
                //disable next button
                nextPageStatus="disabled";
        }else{
                nextPageStatus="enabled";      
        }
        thumbPG.innerHTML="<a id='prevPage' class='"+prevPageStatus+"' href='#' title='Previous' onclick='slideshow(\"stop\"); scrollToThumbPage("+prev+"); return false;'></a><div>Page "+thumbPage+" of "+pages+"</div><a id='nextPage' class='"+nextPageStatus+"' href='#' title='Next' onclick='slideshow(\"stop\"); scrollToThumbPage("+next+"); return false;'></a>";
}
function launchFullSize(carId, ImageToFocus){
        height=550;
        width=775;
        //newWin=window.open("images.php?id="+carId+"#"+ImageToFocus,"gallery","status=0, toolbar=0, scrollbars=1, width="+width+"px, height="+height+"px");
        // RALUCA: script name and parameters changed to values used in the code
        //          sHttpHost must be defined in the HTML page where the function is called
        if (stockPictureUri != '')
          newWin=window.open("http://"+sHttpHost+"/inventory/vehicle/pictures/fullSize.php?stockpictureuri="+stockPictureUri+"&vehicleid="+carId+"#"+ImageToFocus,"gallery","status=0, toolbar=0, scrollbars=1, width="+width+"px, height="+height+"px");
        else newWin=window.open("http://"+sHttpHost+"/inventory/vehicle/pictures/fullSize.php?vehicleid="+carId+"#"+ImageToFocus,"gallery","status=0, toolbar=0, scrollbars=1, width="+width+"px, height="+height+"px");
        //center on screen
        winH = screen.height;
        winW = screen.width;
        newWin.moveTo((winW-width)/2,(winH-height)/2);
        newWin.focus();
}

/*installed options min/max script*/
function initOptions(){
        //alert("Init options");
        show = 8;//number of options to show initially
        splitInto = 2;//number of sub lists to divide into
        //grab all li's with a class of 'optionItem'
        optionItems = document.getElementsByTagName("LI");
        optionList = [];
        for(i=0; i<optionItems.length; i++){
                if(optionItems[i].className=="optionItem"){
                        optionList.push(optionItems[i].innerHTML);      
                }
        }
        if(optionList.length<show){
                show=optionList.length;
        }
        //set list to minimise
        formatOptions("0");
        //unhide options (hidden by css)
        document.getElementById("optionWrapper").style.display="block";
}
function formatOptions(act){
        if(act=="0"){
                count = show;
        }else{
                count = optionList.length;      
        }
        //generate new uls(store each list in an array)
        lists = [];
        for(i=0; i<count; i++){
                //which list are we adding to?
                arr = Math.ceil((i+1)/(count/splitInto));
                //if current array is empty, add a blank string
                if(lists[arr]==null){lists[arr]="";}
                lists[arr]+="<li class='optionItem'>"+optionList[i]+"</li>";
        }
        //add a minimise/maximise link as last option item (only if there are hidden options)
        if(act=="0"){
                //show maximise link
                toggleLink = "<li><a href='#' onclick='formatOptions(1); return false;'>Show all Options</a></li>";
        }else{
                toggleLink = "<li><a href='#' onclick='formatOptions(0); return false;'>Hide Options</a></li>";     
        }
        if(optionList.length>show){
                lists[lists.length-1] += toggleLink;
        }
        //loop through lists (starting at lists[1])
        buffer = "";
        for(i=1; i<=lists.length-1; i++){
                //alert(lists[i]);
                buffer += "<ul class='bulleted'>"+lists[i]+"</ul>";
        }
        //replace original list with minimised, divided one
        document.getElementById("optionWrapper").innerHTML=buffer;
}

/*----------------------------------------------------------------------------------------*/

/*carousel JS for similar vehicles panel - NOT CURRENTLY USED*/
function initSimilar(){
        //alert("init similar");
        //current view tracker
        viewing = 1;//initial page to view
        perPage = 3;//how many vehicles per page
        //grab all divs from document
        divs = document.getElementsByTagName("DIV");
        //add divs with the class 'similar' to an array
        similarList = [];
        for(i=0; i<divs.length; i++){
                if(divs[i].className=="similar"){
                        similarList.push(divs[i].innerHTML);    
                }
        }
        //split the vehicle array into new array grouped in 3's
        groups = [];
        for(i=0; i<similarList.length; i++){
                arr=Math.ceil((i+1)/perPage);
                //if current array value is empty, initialise it with an empty string (stops 'undefined' appearing)
                if(groups[arr]==null){groups[arr]=""}
                //add the content for current vehicle, wrap it in a div tag with 'similar' class
                groups[arr] += "<div class='similar'>"+similarList[i]+"</div>";
        }
        //unhide the similar vehicle panel and prev/next buttons (hidden by css)
        document.getElementById("moreLikeThis").style.display="block";
        //document.getElementById("similarControls").style.display="block";//not used atm
        //call group ordering function
        reArrange();
        return true;
}
function step(direction){
        if(scrolling==false){
                if(direction=="0"){
                        //alert("current"+viewing);
                        viewing = viewing-1;
                        if(viewing < 1){viewing=groups.length-1;}
                        //alert("previous"+viewing);
                        //alert("left");
                        scrolling=true;
                        $('div#similarViewport').scrollTo("#leftGroup", 500, {axis:'x', onAfter:function(){reArrange();}});
                        centerViewport();
                }else{
                        //alert("current"+viewing);
                        viewing = viewing+1;
                        if(viewing > groups.length-1){viewing=1;}
                        //alert("next"+viewing);
                        //alert("right");
                        scrolling=true;
                        $('div#similarViewport').scrollTo("#rightGroup", 500, {axis:'x', onAfter:function(){reArrange();}});
                        centerViewport();
                }
                return true;
        }
}
function reArrange(){
        //alert("rearrange");
        //reassemble the groups into the correct order and add id's for scrolling (only need to show 3 groups - current and 1 either side)
        //previous group
        prevGroup = viewing-1;
        if(prevGroup < 1){prevGroup=groups.length-1;}
        //next group
        nextGroup = viewing+1;
        if(nextGroup > groups.length-1){nextGroup=1;}
        buffer="";
        buffer += "<div id='leftGroup' class='group'>"+groups[prevGroup]+"</div>";
        buffer += "<div id='middleGroup' class='group'>"+groups[viewing]+"</div>";
        buffer += "<div id='rightGroup' class='group'>"+groups[nextGroup]+"</div>";
        //replace similar vehicle wrapper html with new code
        //alert(buffer);
        document.getElementById("similarWrapper").innerHTML=buffer;
        centerViewport();
        scrolling=false;
        return true;
}
function centerViewport(){
        //center viewport on current group
        //alert("centering");
        $('div#similarViewport').scrollTo("#middleGroup", 0, {axis:'x'});
        return true;
}

/*account management*/
var showSection = function(sectionLinkId){
	if(!sectionLinkId){
		var sid=1;
	}else{
		var sid=sectionLinkId.substring(4);
	}
	var title=document.getElementById('link'+sid).innerHTML;
	var sections = document.getElementById('sections').getElementsByTagName("LI");
	for(i=0; i<sections.length; i++){
		if(sections[i].className=='section'){
			if(sections[i].id.substring(1)==sid){
				sections[i].style.display="block";
			}else{
				sections[i].style.display="none";
			}
		}
	}
	//show active section in list
	var sLinks = document.getElementById("sectionLinks").getElementsByTagName("A");
	for (i=1; i<=sLinks.length; i++){
		document.getElementById('link'+i).className="";
	}
	document.getElementById('link'+sid).className="on";
	//update breadcrumb location/section title
	document.getElementById('sTitleTop').innerHTML=title;
	document.getElementById('currentLoc').innerHTML=title;
}
var expandSection = function(childId){
	var childItem = document.getElementById(childId);
	var curState = childItem.className;
	var targetClass;
	switch(curState){
	case 'activeChild':targetClass='inactiveChild';
	break;
	case 'inactiveChild':targetClass='activeChild';
	break;
	default:targetClass='activeChild';
	}
	childItem.className=targetClass;
	//set siblings to be inactive
	var siblingItems = childItem.parentNode.childNodes;
	//compare the first char of each el, to see if it's a sibling of the active item
	for(i=0; i<siblingItems.length; i++){
		if(siblingItems[i].id && siblingItems[i].id.substr(0,1)==childItem.id.substr(0,1) && siblingItems[i]!==childItem && siblingItems[i].id.substr(0,1)!=='v'){
			siblingItems[i].className='inactiveChild';
		}
	}
}
var showSaved = function(msgId){
	window.saveMsg = msgId;
	document.getElementById(msgId).style.visibility="visible";
	//document.getElementById(msgId).style.opacity=100;
	setTimeout('hideSaved(saveMsg)',5000);
}
//temp function to hide saved message - make fade evenually
var hideSaved = function(msgId){
	document.getElementById(msgId).style.visibility="hidden";
}
//toggle photo upload forms
var toggleUploadForm = function(id){
	var formWrapper = document.getElementById(id).parentNode;
	var curState = formWrapper.className;
	if (curState.search(/max/)>-1){
		formWrapper.className = curState.replace("max","min");
	}else{
		formWrapper.className = curState.replace("min","max");
	}
}

/* Added by Raluca 
 This function is used by the UserData.js to display validation errors for user data (profile & settings)
 Feel free to change the design as you please
 
 The hErrors it's an associative array (fieldname=>errorMessage)
 Usage : Display error message for the field [fieldname]
   if (hErrors[fieldname])
     DisplayErrorCode(hErrors[fieldname]);
 List of fields: 
         D_firstname_Z, D_latsname_Z, D_gender_Z, D_birthdate_Z,
         D_cityid_Z, D_alternatecityid_Z, D_countryid_Z,
         D_language_Z, D_textsize_Z, D_resultsperpage_Z, D_defaultsortfield_Z,
         oldpword, newpword1, newpword2, deletereason         
*/        
function DisplayUserSettingsErrors(msgId, hErrors)
{
  var sMsg = '';
  for(var i in hErrors)
    sMsg += "<br />"+i+": "+hErrors[i];
  var msgElem = document.getElementById(msgId);
  msgElem.innerHTML = sMsg;
  msgElem.setAttribute("class", "error");
  msgElem.style.visibility="visible";
  
  // hide the error after a while or do something else to make the message dissapear when calling showSaved
  window.errMsg = msgId;
  setTimeout('hideSaved(errMsg)',5000);
}

/*Vehicle detail page*/
var showTafForm = function(){
	document.getElementById("tafForm").style.display="block";       
	document.getElementById("pageMaskPop").style.display="block";
	document.getElementById("recipient_email").focus();
	window.scroll(0,0);
}
var showReportForm = function(){
	document.getElementById("reportForm").style.display="block";       
	document.getElementById("pageMaskPop").style.display="block";	
	window.scroll(0,0);
}
var hideTafForm = function(){
	document.getElementById("tafForm").style.display="none";       
	document.getElementById("pageMaskPop").style.display="none";	
}
var hideReportForm = function(){
	document.getElementById("reportForm").style.display="none";       
	document.getElementById("pageMaskPop").style.display="none";	
}

/*save search popup*/
var showSSForm = function(){
	document.getElementById("searchSaveForm").style.display="block";  
	document.getElementById("pageMaskPop").style.display="block";
	window.scroll(0,0);
}
var hideSSForm = function(){
	document.getElementById("searchSaveForm").style.display="none";
	document.getElementById("pageMaskPop").style.display="none";	
}

/*Toggle panel expand/collapse (homepage panels)*/
var togglePanel = function(trigger){
	var panel = document.getElementById(trigger).parentNode.parentNode;
	var curState = panel.className;
	if(curState.search(/show/)>-1){
		panel.className=panel.className.replace("show","hide");
	}else{
		panel.className=panel.className.replace("hide","show");
	}
}

/*determine useable (-scrollbars) height of window*/
/*NOTE this is set up for a design width of 960px*/
function getHeight(){
  var vph = 0;
  var browserAdjust = 0;
  if( typeof( window.innerHeight ) == 'number' ) {
    //MOZ uses this
	vph = window.innerHeight;
	vpw = window.innerWidth;
	//does the page have a horizontal scrollbar?
  	if(vpw<987){//986px or less will require scrolling in mozilla
	  browserAdjust -= 16;
  	}
  }else if(document.documentElement && document.documentElement.clientHeight) {
    //IE uses this
	vph = document.documentElement.clientHeight;
	vpw = document.documentElement.clientWidth;
  }else if(document.body && document.body.clientHeight) {
   //OTHERS USE THIS
   vph = document.body.clientHeight;
   vpw = document.body.clientWidth;
  }
  return(vph+browserAdjust);
}

/*find position of an element on screen*/
function getElementPosition(elemID){
	var offsetTrail = document.getElementById(elemID);
	var offsetLeft = 0;
	var offsetTop = 0;
	while (offsetTrail){
		offsetLeft += offsetTrail.offsetLeft;
		offsetTop += offsetTrail.offsetTop;
		offsetTrail = offsetTrail.offsetParent;
	}
	if (navigator.userAgent.indexOf('Mac') != -1 && typeof document.body.leftMargin != 'undefined'){
		offsetLeft += document.body.leftMargin;
		offsetTop += document.body.topMargin;
	}
	return {left:offsetLeft,top:offsetTop};
}

/*find how far the page has been scrolled*/
function getScrollY(){
  var scrOfY = 0;
  if( typeof(window.pageYOffset) == 'number' ) {
    scrOfY = window.pageYOffset;
  } else if(document.body && document.body.scrollTop) {
    scrOfY = document.body.scrollTop;
  } else if(document.documentElement && document.documentElement.scrollTop) {
    scrOfY = document.documentElement.scrollTop;
  }
  return(scrOfY);
}

/*browser detect*/
function getBrowser(){
	var b='';
	//if(!document.all && !window.opera && document.getElementById;){b='ns6'};
	//if(window.opera && document.createComment){b='op7>'};
	//if(window.opera && !document.createComment){'<op7'};
	//if(document.all && document.getElementById && !document.mimeType && !windows.opera;){b='ie5mac'};
	if(document.all && document.fireEvent && document.createComment){b='ie6'};
	return b;
}

/*animated vehicle thumbnail flipping*/
function AT_initThumbs(id,show,delay){
		var listEl = document.getElementById(id);
		listEl.vA = Array();
		var items = listEl.getElementsByTagName('LI');
		for(i=0; i<items.length; i++){
			var p = Array();
			var img = items[i].getElementsByTagName('IMG')[0];
			p[0]=img.src;
			if(!listEl.oW){
					listEl.oW=img.offsetWidth-4;
					listEl.oH=img.offsetHeight-4;
			}
			var a = items[i].getElementsByTagName('A')[0];
			p[1]=a.href;
			p[2]=a.title;
			p[3]=items[i].getElementsByTagName('SPAN')[0].innerHTML;
			listEl.vA[listEl.vA.length]=p;
			a.onmouseover=function(){AT_pause(this.parentNode.parentNode.id);};
			a.onmouseout=function(){AT_resume(this.parentNode.parentNode.id);};
			items[i].style.width=img.offsetWidth+"px";
		}
		listEl.index=show-1;
		listEl.delay=delay;
		listEl.show=show;
		listEl.changing=false;
		for(i=0; i<show; i++){
				var el = listEl.getElementsByTagName('LI')[i];
				el.style.display='block';
				el.id=id+i;
		}
		if(items.length>show){
			var pagButs = listEl.parentNode.getElementsByTagName("DIV");
			for (i=0; i<pagButs.length; i++){
				pagButs[i].style.display="block";
			}
			listEl.d = setInterval(function(){AT_loadNext(id);},delay*1000);
		}
}
function AT_pause(id){
	clearInterval(document.getElementById(id).d);
}
function AT_resume(id){
	var listEl = document.getElementById(id);
	listEl.d = setInterval(function(){AT_loadNext(id);},listEl.delay*1000);
}
function AT_reset(id){
	var listEl = document.getElementById(id);
	if(listEl.d){
		clearInterval(listEl.d);
		listEl.d = setInterval(function(){AT_loadNext(id);},listEl.delay*1000);
	}
}
function degToRad(val){
	return val*(Math.PI/180);
}
function AT_loadNext(id){
	var listEl = document.getElementById(id);
	listEl.changing=true;
	AT_animate(listEl.getElementsByTagName('LI')[0].getElementsByTagName('IMG')[0]);
}
function AT_nextGroup(id){
	var listEl = document.getElementById(id);
	if(listEl.changing==false){
		AT_reset(id);
		AT_loadNext(id);
	}
}
function AT_prevGroup(id){
	var listEl = document.getElementById(id);
	if(listEl.changing==false){
		var v = listEl.vA.length;
		var	prev = (listEl.index-(listEl.show*2));
		if(prev<0){
			prev=v+prev;
		}
		listEl.index = prev;
		AT_reset(id);
		AT_loadNext(id);
	}
}
function AT_cascade(obj){
	var listItem = obj.parentNode.parentNode;
	var listEl = listItem.parentNode;
	var items = listEl.getElementsByTagName('LI');
	for(i=0; i<items.length; i++){
		if(items[i]==listItem){
			var next = i+1;
		}
	}
	if(next<items.length){
		if(items[next].style.display=='block'){
			AT_animate(items[next].getElementsByTagName('IMG')[0]);
		}else{
			listEl.changing = false;
		}
	}
}
function AT_getNext(obj){
	var listItem = obj.parentNode.parentNode;
	var listEl=listItem.parentNode;
	var vI = listEl.index+1;
	if(vI>listEl.vA.length-1){
		vI=0; listEl.index=0;
	}else{
		listEl.index=vI;
	}
	var data = listEl.vA[vI];
	obj.src=data[0];
	listItem.getElementsByTagName('A')[0].href=data[1];
	listItem.getElementsByTagName('A')[0].title=data[2];
	var target = listItem.getElementsByTagName('SPAN')[0];
	target.innerHTML=data[3];
}
var AT_animate = function(obj){
	var info = obj.parentNode.getElementsByTagName('SPAN')[0];
	if(!obj.rA){
		obj.rA=90;
	}
	var listEl = obj.parentNode.parentNode.parentNode;
	var tW = listEl.oW;
	var tH = listEl.oH;
	var width = Math.abs(Math.round((Math.sin(degToRad(obj.rA))*tW)));
	var fxPc = 100-(tW-width);
	var rightShift = (width/2)-(tW/2);
	obj.style.width = width+"px";
	obj.style.height = tH+"px";
	obj.style.right = rightShift+"px";
	obj.style.opacity = fxPc/100;
	obj.style.filter = 'alpha(opacity=' + fxPc + ')';
	info.style.bottom = (tW-width)/2+"px";
	info.style.opacity = fxPc/100;
	info.style.filter = 'alpha(opacity=' + fxPc + ')';
	obj.rA+=10;
	if(obj.rA==150){
		AT_cascade(obj);
	}
	if(obj.rA==180){
		AT_getNext(obj);
	}
	if(obj.rA==270){
			obj.rA=90;
	}else{
		setTimeout(function(){AT_animate(obj);},15);
	}
}

// TODO
function DisplayShareVehicleErrors(hErrors)
{
  var sMsg='';
  for (var i in hErrors)
    sMsg += "<br />"+i+": "+hErrors[i];
  alert("Errors: "+sMsg);
}

// TODO
function DisplayShareVehicleSuccess()
{
  alert("Share vehicle success");
}


//
// Alter the document after the vehicle has been successfully saved to 
// the user's favorites list
//
// @param   elemId    Id of the html element that represents the "save to favorites" link
// @paaram  parentId  Id of the elemId parent html element 
// @param   msg       Message to be displayed
// @param   lg        The current language 2 character ISO code (en/ro/...)
// 
function DisplaySavedToFavorites(childId, parentId, msg, lg)
{
  //create the a elelment to display the text
  /*
	var oLink = document.createElement("a");
  oLink.setAttribute("href","#");
  oLink.setAttribute("class","AHBut dis");
  oLink.setAttribute("title",sDisplayText);
  oLink.setAttribute("style","visibility: inherit;");
  oLink.innerHTML = "<del><div class='but_outer'><div class='but_inner'><div class='but_bg'>&nbsp;</div><div class=but_label>"+msg+"</div></div></div></del>";
  
  var parent = document.getElementById(parentId);
  */
	var elem = document.getElementById(childId);
  if (elem != null)
    //parent.replaceChild(oLink, elem);
  	//else parent.appendChild(oLink);
		/*
		TODO:
		pass a language variable to this function, so we can set the correct class - 'enadded' or 'roadded'
		for now, just set to romanian version
		*/
		elem.className = 'shortlist roadded';
}


//
// Dipsplay validation errors to the 'contact seller form'
// 
// @param  hErrors  Assoc array [fieldName]=>[ErrorMessage]
//
function DisplayContactSellerErrors(hErrors)
{
  // reset all error fields 
  var aErrorFields = ['error_name_last', 'error_email', 'error_phone', 'error_message', 'error_subject', 'error_send_CC', 'error_subscribe'];
  for(var i=0; i<aErrorFields.length; i++)
  {
    var elem = document.getElementById(aErrorFields[i]);
    if(elem)
      elem.innerHTML = '';
  }
  
  for (var i in hErrors)
  {
    var elem = document.getElementById('error_'+i);
    if (elem)
      elem.innerHTML = "<span class='error smaller' style='display:-moz-inline-box; display:inline-block; padding-top:5px;'>"+hErrors[i]+"</span>";
  }
}

//
// Dipsplay contact seller success messages
//
// @param  hStatus  Assoc array 'sellerEmail' => [success status: 1/0]
//                              'userEmail' =>[undefined / success status : 1/0]
//
function DisplayContactSellerSuccess(hStatus)
{
  //reset all error fields 
  var aErrorFields = ['error_name_last', 'error_email', 'error_phone', 'error_message', 'error_subject'];
  for(var i=0; i<aErrorFields.length; i++)
  {
    var elem = document.getElementById(aErrorFields[i]);
    if (elem)
      elem.innerHTML = '';
  }
  //var sMsg = 'Send seller email : '+(hStatus['sellerEmail'] > 0 ? 'SUCCESS' : 'FAILED');
  //if(hStatus['userEmail'])
  //	sMsg = sMsg + "\nUser email copy: "+(hStatus['userEmail'] > 0 ? "SUCCESS" : "FAILED");
	var sMsg = "";
	if(hStatus['sellerEmail'] <= 0){
		sMsg = "Error: we could not send your message to the seller at this time. Please try again later.";
	}else{
		if(hStatus['userEmail']){
			if(hStatus['userEmail'] <= 0){
				sMsg = 'We managed to send your message to the seller, but we couldn\'t send a copy to yourself. There is no need to resend your message.';
			}
		}
	}
	//if errors, show alert
	if(sMsg!==""){
		alert(sMsg);
	}
	if(hStatus['sellerEmail'] > 0){
		//switch class of button wrapper to show sent & reset button
		var butElWrap = document.getElementById('cSButWrapper');
		butElWrap.className = 'sent';
	}
}
function resetCSForm(){
	document.getElementById('contactSeller').reset();
	var butElWrap = document.getElementById('cSButWrapper');
	butElWrap.className = 'send';
}
//text size switcher on article page
var textSize = function(size, linkId){
	var target = document.getElementById("scaleable");
	switch(size){
		case 1:target.style.fontSize="100%";
		break;
		case 2:target.style.fontSize="1.16em";
		break;
		case 3:target.style.fontSize="1.33em";
		break;
	}
	//remove class names from all text size links
	var sizeLinks = document.getElementById('textSize').getElementsByTagName("A");
	for(i=0; i<sizeLinks.length; i++){
		sizeLinks[i].className="";	
	}
	//set current text size link class to hilight
	document.getElementById(linkId).className="currentSize";
}

//adds text overlay on article images with the class of 'captioned' (as set in modx)
var showArticleImageCaptions = function(){
	var wrapper = document.getElementById("article");
	var articleImages = wrapper.getElementsByTagName("IMG");
	for(i=0; i<articleImages.length; i++){
		if(articleImages[i].className.search(/captioned/)>-1){
			var captionText = articleImages[i].getAttribute("title");
			if(captionText!==null){
				var source= articleImages[i];
 				var fragment= document.createDocumentFragment();
 				var newImgWrap = document.createElement("div");
				if(articleImages[i].className.search(/left/)>-1){
					newImgWrap.className="modxImageWrapperLeft";
				}else{
					newImgWrap.className="modxImageWrapperRight";	
				}
				var cWrap = document.createElement("div");
				cWrap.className = "modxCaptionWrapper";
				var caption = document.createElement("span");
				caption.className="modxImageCaption";
				caption.appendChild(document.createTextNode(captionText));
				cWrap.appendChild(caption);
				newImgWrap.appendChild(cWrap);
 				newImgWrap.appendChild(source.cloneNode(true));
				fragment.appendChild(newImgWrap);
 				source.parentNode.replaceChild(fragment, source);
			}
		}
	}
}

//show/hide benefits in header - NEEDS WORK!
if(document.getElementById('benefitWrapper')){
	var header = document.getElementById('head');
	header.minH = 66;
	header.maxH = 80 + document.getElementById('benefitWrapper').offsetHeight;
	//alert(document.getElementById('benefitWrapper').offsetHeight);
	function showBenefits(){
		if(header.cHeight>header.minH){
			header.tHeight = header.minH;
		}else{
			header.tHeight = header.maxH;
		}
		animateHeader();
	}
	function hideBenefits(){
		header.tHeight = header.minH;
		animateHeader();
	}
	function animateHeader(){
		if(!header.cHeight){
			header.cHeight = header.offsetHeight;
		}
		var tH = header.tHeight;
		var cH = header.cHeight;
		var move = Math.abs(tH-cH)/3;
		if(tH>cH){
			header.cHeight += move; 
		}else{
			header.cHeight -= move;
		}
		header.style.height = header.cHeight + "px";
		if(move>.2){
			if(header.tO){
				clearTimeout(header.tO);
			}
			header.tO = setTimeout('animateHeader()',10);
		}else{
			header.cHeight = header.tHeight;
		}
		
		//force a redraw of the page for FF2 - NEEDS WORK
		redraw('contentWrapper');
		
		if(header.cHeight == header.maxH){
			document.getElementById('benefitWrapper').style.visibility='visible';
			document.getElementById('bTab').style.display='block';
		}else{
			document.getElementById('benefitWrapper').style.visibility='hidden';
			document.getElementById('bTab').style.display='none';
		}
	}
}
function redraw(el){
	element = document.getElementById(el)
	var n = document.createTextNode(' ');
	element.appendChild(n);
	n.parentNode.removeChild(n);
	return element;
}

//expand search criteria list (account management pages)
function toggleCriteria(id, trigger, showText, hideText){
  var cTab = document.getElementById(id);
  var cLink = document.getElementById(trigger);
  if(!cTab.expanded){
    cTab.expanded = true;
  }
  var rows = cTab.getElementsByTagName("LI");
  for(i=0; i<rows.length; i++){
    if(rows[i].className.search(/expHide/)>=0){
      rows[i].className = rows[i].className.replace('expHide','expShow');
      cTab.expanded = true;
    }else{
      if(rows[i].className.search(/expShow/)>=0){
        rows[i].className = rows[i].className.replace('expShow','expHide');
        cTab.expanded = false;
      }
    }
  }
  if(cTab.expanded){
    cLink.innerHTML = hideText;
  }else{
    cLink.innerHTML = showText;
  }
}