// DF1.1 :: domFunction 
// *****************************************************
// DOM scripting by brothercake -- http://www.brothercake.com/
// GNU Lesser General Public License -- http://www.gnu.org/licenses/lgpl.html
//******************************************************

//DOM-ready watcher
function domFunction(f, a)
{
	//initialise the counter
	var n = 0;
	
	//start the timer
	var t = setInterval(function()
	{
		//continue flag indicates whether to continue to the next iteration
		//assume that we are going unless specified otherwise
		var c = true;

		//increase the counter
		n++;
	
		//if DOM methods are supported, and the body element exists
		//(using a double-check including document.body, for the benefit of older moz builds [eg ns7.1] 
		//in which getElementsByTagName('body')[0] is undefined, unless this script is in the body section)
		if(typeof document.getElementsByTagName != 'undefined' && (document.getElementsByTagName('body')[0] != null || document.body != null))
		{
			//set the continue flag to false
			//because other things being equal, we're not going to continue
			c = false;

			//but ... if the arguments object is there
			if(typeof a == 'object')
			{
				//iterate through the object
				for(var i in a)
				{
					//if its value is "id" and the element with the given ID doesn't exist 
					//or its value is "tag" and the specified collection has no members
					if
					(
						(a[i] == 'id' && document.getElementById(i) == null)
						||
						(a[i] == 'tag' && document.getElementsByTagName(i).length < 1)
					) 
					{ 
						//set the continue flag back to true
						//because a specific element or collection doesn't exist
						c = true; 

						//no need to finish this loop
						break; 
					}
				}
			}

			//if we're not continuing
			//we can call the argument function and clear the timer
			if(!c) { f(); clearInterval(t); }
		}
		
		//if the timer has reached 60 (so timeout after 15 seconds)
		//in practise, I've never seen this take longer than 7 iterations [in kde 3 
		//in second place was IE6, which takes 2 or 3 iterations roughly 5% of the time]
		if(n >= 60)
		{
			//clear the timer
			clearInterval(t);
		}
		
	}, 250);
};

var preInitialiseShortlist = new domFunction(function()
{		
    initialiseShortlist();                        
}, { 'ShowRoomTable' : 'id', 'ShowRoomTableContainer' : 'id' });


function alreadyInList(name, value)
            {
                var cookieArray = (unescape(document.cookie)).split(';');
                var cookieName = '';
                var startPos;
                for(i=0; i<cookieArray.length; i++)
                {
                    cookieName = trim(cookieArray[i].substr(0, cookieArray[i].indexOf('='))); 
                    if (cookieName!='')
                    {        
                        if(cookieArray[i].indexOf(value) > 0 && cookieName.substr(0,name.length) == name)
                        {
                            break;         
                        }
                        else
                        {
                            cookieName = '';
                        }
                    }
                }

                return cookieName;
            }												
            
            function pageWidth()
            {
                return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;} function pageHeight() {return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
            } 
        
            function pageHeight() 
            {
                return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
            } 
            
            function getNextNumber(name)
            {
                //This function is used to get the next number of the cookie name. This is so that the 
                //users can have several cookies (6 in total) stored for each of their selections
                var cookieArray = unescape((document.cookie)).split(';');
                var nextNumber = 1;
                var currentNumber;
                var cookieName;
        
                //Loop around the array
                for(i=0; i<cookieArray.length; i++)
                {
                    cookieName = trim(cookieArray[i].substr(0, cookieArray[i].indexOf('=')));
                    if(cookieName.substr(0, 8) == 'Showroom')
                    {
                        currentNumber = parseInt(cookieName.substr(cookieName.length - 1, 1));
                        if(currentNumber == nextNumber)
                            nextNumber++;
                    }
                }
                if(nextNumber > 10)
                {
                    alert('You may only have up to 10 cars saved in your list');
                    return -1;
                }
                else	  
                  return nextNumber;
            }
   
            function setCookie(name, value, expires, path, domain, secure)
            {    
                //Get the key and value for the OrderID	  
                var orderValue = value.substr(value.indexOf('OrderID='))
                var cookieName = alreadyInList("Showroom", orderValue);        

                //set up the value of the cookie
                var nextNumber = getNextNumber(name);

                if(nextNumber > 0)
                {
                    if(cookieName == '')
                    {
                        var curCookie = name + String(nextNumber) + '=' + swapSpace(value, true) +
                        ((expires) ? '; expires=' + expires : '') +
                        ((path) ? '; path=' + path : '') +
                        ((domain) ? '; domain=' + domain : '') +
                        ((secure) ? '; secure' : '');
            
                        //Create the cookie
                        document.cookie = curCookie;
                        //alert("Advert saved sucessfully.  This is located in the search box.");

                        //Set the icon to remove
                        if(document.getElementById("addRemoveIcon_" + orderValue))
                        {
                            document.getElementById("addRemoveIcon_" + orderValue).src="/commonfiles/images/removeIcon.gif";            
                        }
                        /*else if(top.window.opener.document.getElementById("addRemoveIcon_" + orderValue)){
                        top.window.opener.document.getElementById("addRemoveIcon_" + orderValue).src="/commonfiles/images/removeIcon.gif";            
                        }*/
        
                        var addremovefromshortlist = document.getElementById("addremovefromshortlist");
                        addremovefromshortlist.innerHTML="Unsave this car";
                    }
                    else
                    {      
                        //alert('Already in your list');
                        //Delete the cookie if it is already in the list        
                        deleteCookie(cookieName, path, domain);
                        if(document.getElementById("addRemoveIcon_" + orderValue))
                        {
                            document.getElementById("addRemoveIcon_" + orderValue).src="/commonfiles/images/addIcon.gif";
                        }
                        /*else if(top.window.opener.document.getElementById("addRemoveIcon_" + orderValue)){
                        top.window.opener.document.getElementById("addRemoveIcon_" + orderValue).src="/commonfiles/images/addIcon.gif";
                        }*/       
                    }
                }   
    
                var cookieName = alreadyInList("Showroom",orderValue);        
        
                if(cookieName == '')
                {
                    var addremovefromshortlist = document.getElementById("addremovefromshortlist");
                    addremovefromshortlist.innerHTML="Save this car";                
                }        
    
                var viewshortlist = document.getElementById("viewshortlist");
        
                if (numberInList()==1)
                    viewshortlist.innerHTML="Saved cars (1 car)";                                
                else
                    viewshortlist.innerHTML="Saved cars (" + numberInList() + " cars)";                                
        
                if (numberInList()>0)        
                    showShortList();
                else
                    hideShortList();
            }

  /* Mod 01/03/2010 */  
  function setCookieTest(name, value, expires, path, domain, secure)
  {    
    //Get the key and value for the OrderID	  
    var orderValue = value.substr(value.indexOf('OrderID='))
    var cookieName = alreadyInList(orderValue);        

    //set up the value of the cookie
    var nextNumber = getNextNumber(name);
    cookieName = '';

    if(nextNumber > 0){
      if(cookieName == '')
      {
        var curCookie = name + String(nextNumber) + '=' + swapSpace(value, true) +
            ((expires) ? '; expires=' + expires : '') +
            ((path) ? '; path=' + path : '') +
            ((domain) ? '; domain=' + domain : '') +
            ((secure) ? '; secure' : '');
            
        //Create the cookie
        document.cookie = curCookie;
        //alert("Advert saved sucessfully.  This is located in the search box.");

        //Set the icon to remove
        if(document.getElementById("addRemoveIcon_" + orderValue)){
          document.getElementById("addRemoveIcon_" + orderValue).src="/commonfiles/images/removeIcon.gif";            
        }
        /*else if(top.window.opener.document.getElementById("addRemoveIcon_" + orderValue)){
          top.window.opener.document.getElementById("addRemoveIcon_" + orderValue).src="/commonfiles/images/removeIcon.gif";            
        }*/
        
        var addremovefromshortlist = document.getElementById("addremovefromshortlist");
        addremovefromshortlist.innerHTML="Unsave this car";
      }
      else{      
        //alert('Already in your list');
        //Delete the cookie if it is already in the list
        deleteCookie(cookieName, path, domain);
        if(document.getElementById("addRemoveIcon_" + orderValue)){
          document.getElementById("addRemoveIcon_" + orderValue).src="/commonfiles/images/addIcon.gif";
        }
        /*else if(top.window.opener.document.getElementById("addRemoveIcon_" + orderValue)){
          top.window.opener.document.getElementById("addRemoveIcon_" + orderValue).src="/commonfiles/images/addIcon.gif";
        }*/       
      }
    }   
    
  
    var viewshortlist = document.getElementById("viewshortlist");
        
    if (numberInList()==1)
        viewshortlist.innerHTML="Saved cars (1 car)";                                
    else
        viewshortlist.innerHTML="Saved cars (" + numberInList() + " cars)";                                
  }
  /* End of mod 01/03/2010 */  
  
  function deleteCookie(name, path, domain){
    //If the cookie exists, set the expiry to timesomewhere way in the past
    var curCookie = name + '=' + 
      ((path) ? '; path=' + path : '') +
      ((domain) ? '; domain=' + domain : '') + 
      '; expires=Thu, 01-Jan-70 00:00:01 GMT';        

    document.cookie = curCookie;
    //alert("Advert unsaved sucessfully");
  }
            var page=0;
            
            function prevPage()
            {                    
                    if (page>0)
                        page--;
                        
                    createShortListHTML();
            }
            
            function nextPage()
            {
                    var carsPerPage = Math.floor(pageWidth()*0.9/170);
                    var carsInList = numberInList();
                    
                    var numberOfPages = Math.ceil(carsInList/carsPerPage);
                    
                    if (page<numberOfPages)
                        page++;
                        
                    createShortListHTML();
            }
            
            /* Mod 01/03/2010 */
            function setAddRemove()
            {
                var addremovefromshortlist = document.getElementById('addremovefromshortlist'); 
		if (addremovefromshortlist)
			addremovefromshortlist.innerHTML='Save this car';
                
                if (numberInList()>0)        
                    showShortList();
                else
                    hideShortList();                
            }
            /* End of Mod 01/03/2010 */
            
            
            /* Mod 01/03/2010 */
            function setShowRoomTitle()
            {
                var shortlistTitle = document.getElementById('shortlistTitle');  
                shortlistTitle.innerHTML = "";
                if(numberInList() == 0)
                {                   
                    shortlistTitle.innerHTML += 'Saved cars - no cars saved (Max 10)';                                 
                    //htmlString = htmlString + '<tr><td>No cars saved</td></tr>';                                 
                }
                else
                {
                    if (numberInList()==1)                    
                        shortlistTitle.innerHTML += 'Saved cars - ' + numberInList() + ' car in Shortlist (Max 10)';
                    else
                        shortlistTitle.innerHTML += 'Saved cars - comparing ' + numberInList() + ' cars (Max 10)';                                        
                }
            }
            /* End of Mod 01/03/2010 */
           
            /* Mod 01/03/2010 */
            function createShortListHTML()
            {     	 	      
                var htmlString = '';
                var cookieArray = (unescape(document.cookie)).split(';');
                var cookieName;
                var startPos;
                var cookieValue;
                
                showRoomTable = document.getElementById('ShowRoomTable');

                htmlString = htmlString + '<table cellpadding="0" cellspacing="0"><tr>';
                
                if(page > 0)
                {                                           
                     htmlString = htmlString + '<td background="leftarrowbg.png" bgcolor="#282828" style="background-repeat:repeat-y;background-position-x:right"><table><tr><td><img id="leftarrow" name="leftarrow" src="leftarrow.png" onclick="prevPage();"/></td></tr></table></td>';                                
                }
                
                htmlString = htmlString + '<td>';
                htmlString = htmlString + '<table border="0" cellpadding="0" cellspacing="0" width="100%" bgcolor="#282828">';
                                                
                //Start the row                
                if(numberInList() > 0)
                {                                           
                    htmlString = htmlString + '<tr>';                    
                }
                                
                var carsPerPage = Math.floor(pageWidth()*0.9/170);
                //shortlistTitle.innerHTML = "cars per page = " + carsPerPage;
                                 
                start=page*carsPerPage;
                end=start+carsPerPage;                                    
                
                var carCount=0;
                for(i=0; i<cookieArray.length; i++)
                {
                    //Get the current cookie name
                    cookieName = trim(cookieArray[i].substr(0, cookieArray[i].indexOf('=')));

                    //Get the value of the current cookie
                    var orderValue = cookieArray[i].substr(cookieArray[i].indexOf('OrderID='));

                    //If the cookie is one that is required, then print it
                    if(cookieName.substr(0,8) == 'Showroom')
                    {                        
                        if (carCount>=start&&carCount<end)
                        {
                            //Start the column
                            htmlString = htmlString + '<td width="170px">';
                            cookieValue = swapSpace(cookieArray[i], false);                

                            //Get the Url for the car        
                            startPos = cookieArray[i].indexOf('url=') + 4;
                            var url = cookieValue.substr(startPos, cookieValue.indexOf('&imageurl', startPos) - startPos);

                            //Get the Image of the car
                            startPos = cookieArray[i].indexOf('imageurl=') + 9;
                            
                            var imageSrc;
                            if (cookieValue.substr(startPos)=="")
                                imageSrc="awaitingphoto.gif";
                            else
                                imageSrc=cookieValue.substr(startPos);
                                    
                            htmlString = htmlString + '<table>';
                            htmlString = htmlString + '<tr>';
                            htmlString = htmlString + '<td><a href="' + url + '"><img width="150" height="100" src="' + imageSrc + '"></a></td>';
                            htmlString = htmlString + '</tr>';
        
                            //Get the Make for the car        
                            startPos = cookieArray[i].indexOf('Make=') + 5;
                            var make = cookieValue.substr(startPos, cookieValue.indexOf('&', startPos) - startPos);
        
                            //Get the Model of the car        
                            startPos = cookieArray[i].indexOf('Model=') + 6;
                            var model = cookieValue.substr(startPos, cookieValue.indexOf('&', startPos) - startPos);
        
                            //Display details                                                
                            htmlString = htmlString + '<tr>';
                            htmlString = htmlString + '  <td bgcolor="#333333"><a href="' + url + '"><font size="5" color="#ffffff">' + make + ' ' + model + '</font></a>&nbsp;<a href="" onClick="deleteCookie(\'' + cookieName + '\', \'/\', \'\'); createShortListHTML(); changeAddRemoveIcon(\'' + orderValue + '\'); setAddRemove();return false;" name="deleteCookie" id="deleteCookie"><font color="#ff0000 size="5">[<b>X</b>]</font></a></td>';
                            //htmlString = htmlString + '  <td>' + make + '</td>';
                            htmlString = htmlString + '</tr>';
                
                            //Get the Price of the car
                            startPos = cookieArray[i].indexOf('Price=') + 6;        
                            htmlString = htmlString + '<tr>';
                            htmlString = htmlString + '  <td><font size="5" color="#ffffff">Price: &pound;' + cookieValue.substr(startPos, cookieValue.indexOf('&', startPos) - startPos) + '</font></td>';
                            htmlString = htmlString + '</tr>';        

                            //Get the mileage of the car
                            startPos = cookieArray[i].indexOf('Mileage=') + 8;        
                            htmlString = htmlString + '<tr>';
                            htmlString = htmlString + '  <td bgcolor="#333333"><font size="5" color="#ffffff">Mileage: ' + cookieValue.substr(startPos, cookieValue.indexOf('&', startPos) - startPos) + '</font></td>';
                            htmlString = htmlString + '</tr>'; 

                            //Get the engine of the car
                            startPos = cookieArray[i].indexOf('Engine=') + 7;        
                            htmlString = htmlString + '<tr>';
                            htmlString = htmlString + '  <td><font size="5" color="#ffffff">Engine: ' + cookieValue.substr(startPos, cookieValue.indexOf('&', startPos) - startPos) + '</font></td>';
                            htmlString = htmlString + '</tr>'; 
                            htmlString = htmlString + '</table>';
                            htmlString = htmlString + '</td>';                                                        
                        }
                        
                        carCount++;
                    }
                }
                
                
                for(i=carCount;i<end;i++)
                {                
                    htmlString = htmlString + '<td width="170px">';
                    htmlString = htmlString + '</td>';
                }
                
                
                //End of the table
                /*if(numberInList() > 0)
                {
                	if(showHeader != "")
                		htmlString = htmlString + '<tr><td colspan="4"><a href="compareShowroom.asp?showHeader=' + showHeader + '" target="_blank"><font color="#ff0000"><b>Compare these cars</b></font></a></td></tr>';
    	            else
      	                htmlString = htmlString + '<tr><td colspan="4"><a href="compareShowroom.asp" target="_blank"><font color="#ff0000"><b>Compare these cars</b></font></a></td></tr>';                  
                }
                */
                
                if(numberInList() > 0)
                {                                           
                    htmlString = htmlString + '</tr>';                    
                }
                    
                htmlString = htmlString + '</table>'        
                htmlString = htmlString + '</td>';                    
                
                if(numberInList() > 0)
                {                                           
                    var carsPerPage = Math.floor(pageWidth()*0.9/170);
                    var carsInList = numberInList();                                        
                    if ((page+1)*carsPerPage<carsInList)
                        htmlString = htmlString + '<td background="rightarrowbg.png" bgcolor="#282828" style="background-repeat:repeat-y"><table><tr><td><img id="rightarrow" name="rightarrow" src="rightarrow.png" onclick="nextPage();"/></td></tr></table></td>';                                
                }
    
                htmlString = htmlString + '</tr></table>';
                showRoomTable.innerHTML = htmlString;  
                
                
                var viewshortlist = document.getElementById("viewshortlist");
        
                if (numberInList()==1)
                    viewshortlist.innerHTML="Saved cars (1 car)";                                
                else if (numberInList()>1)
                    viewshortlist.innerHTML="Saved cars (" + numberInList() + " cars)";                                
                    
                setShowRoomTitle();
            }
            /* End of new Mod 01/03/2010 */                        	
            
    
            /* Mod 20/02/2010 */
            function showShortList()
            {
                var ShowRoomTableContainer = document.getElementById("ShowRoomTableContainer");
			    ShowRoomTableContainer.style.visibility = "visible";		
			    //ShowRoomTableContainer.style.top=pageHeight()-200;        										    
			    //ShowRoomTableContainer.style.height=50;
			
			    var minmax = document.getElementById("minmax");
			    minmax.src="http://www.desperateseller.co.uk/pagescripts/images/minimize.png";
			    minmax.onclick=minimizeShortList;
			    
			    createShortListHTML();
			    			    			    
			    var curCookie = 'Showshortlist=1; expires=' + getCurrentDate(1);            
                //Create the cookie
                document.cookie = curCookie;                                
            }    
        
            /* Mod 01/03/2010 */                        	
            function minimizeShortList()
            {
                var ShowRoomTableContainer = document.getElementById("ShowRoomTableContainer");
			    ShowRoomTableContainer.style.visibility = "visible";												    
			    //ShowRoomTableContainer.style.top=pageHeight()-50;        
			    //ShowRoomTableContainer.style.height=50;        
			
			    var minmax = document.getElementById("minmax");
			    minmax.src="http://www.desperateseller.co.uk/pagescripts/images/maximize.png";
    			minmax.onclick=maximizeShortList;
    			document.getElementById('ShowRoomTable').innerHTML = '<table border="0" cellpadding="0" cellspacing="5" width="90%" bgcolor="white"></table>';
    			
    			setShowRoomTitle();
    			    			
    			var curCookie = 'Showshortlist=3; expires=' + getCurrentDate(1);            
                //Create the cookie
                document.cookie = curCookie;                                
            }
            /* End of new Mod 01/03/2010 */                        	
        
            function maximizeShortList()
            {
                var ShowRoomTableContainer = document.getElementById("ShowRoomTableContainer");
			    ShowRoomTableContainer.style.visibility = "visible";												    
			    //ShowRoomTableContainer.style.top=pageHeight()-200;        
			    //ShowRoomTableContainer.style.height=150;        
			
			    var minmax = document.getElementById("minmax");
			    minmax.src="http://www.desperateseller.co.uk/pagescripts/images/minimize.png";
			    minmax.onclick=minimizeShortList;
			    
			    createShortListHTML();
			    
			    var curCookie = 'Showshortlist=2; expires=' + getCurrentDate(1);            
                //Create the cookie
                document.cookie = curCookie;                                
            }
                    
            function hideShortList()
            {
                var ShowRoomTableContainer = document.getElementById("ShowRoomTableContainer");
			    ShowRoomTableContainer.style.visibility = "hidden";												    			
			    var curCookie = 'Showshortlist=0; expires=Thu, 01-Jan-70 00:00:01 GMT';            
                //Create the cookie
                document.cookie = curCookie;                
            }            
            /* End of new Mod 20/02/2010 */                        	
            
            /* Mod 20/02/2010 */
            function initialiseShortlist()
            {            
                var ShowRoomTableContainer = document.getElementById("ShowRoomTableContainer");
                ShowRoomTableContainer.style.visibility = "hidden";		
			            
			    /* Mod 01/03/2010 */
			    //Determine the orderValue for the car so that we know whether it's already saved or not
			    var orderValue = "19045437"; //order value asp variable should be placed here i.e var orderValue = ""; 
			    /* End of Mod 01/03/2010 */
    			//alert(orderValue);
                var cookieName = alreadyInList("Showroom",orderValue);                                                             
                
                if(cookieName != '' && cookieName != 'prefs')                
                {
                    var addremovefromshortlist = document.getElementById("addremovefromshortlist");
                    /* Mod 01/03/2010 */
                    //Just changed "Remove from shortlist" to "Unsave this car"
                    addremovefromshortlist.innerHTML="Unsave this car";
                    /* End of Mod 01/03/2010 */
                }                
                
                var viewshortlist = document.getElementById("viewshortlist");
        
                if (numberInList()==1)
                    viewshortlist.innerHTML="Saved cars (1 car)";                                
                else if (numberInList()>1)
                    viewshortlist.innerHTML="Saved cars (" + numberInList() + " cars)";                                
                    
                var cookieArray = (unescape(document.cookie)).split(';');   
                for(i=0; i<cookieArray.length; i++)
                {                                                            
                    if(cookieArray[i].indexOf("Showshortlist=1") >= 0)
                    {                    
                        showShortList();
                    }                                   
                    else
                    if(cookieArray[i].indexOf("Showshortlist=2") >= 0)
                    {                    
                        maximizeShortList();
                    }                                   
                    else
                    if(cookieArray[i].indexOf("Showshortlist=3") >= 0)
                    {                    
                        minimizeShortList();
                    }                                   
                    
                }
            }                
            /* End of new Mod 20/02/2010 */                        	
            
            /* Mod 16/02/2010 */
            function onLoad()
			{				
			    initialiseShortlist();                        
            }            
            /* End of new Mod 16/02/2010 */                        	
            
            
