/*  JavaScript
    NEWS SUBSET COMMON
    this script will be used across the News subset (news.com.au) websites
*/


/*  ----- support checking -----  */

// detect browser support for getElementById and createElement
var canGetElem = false;
var canCreateElem = false;
if (document.getElementById) {
    canGetElem = true;
    if (document.createElement) {
        canCreateElem = true;
    }
}

/*  ----- end support checking -----  */



/*  ----- global declarations -----  */

// defines the obChg object, used to store info about elemetns that need to be resized in different resolutions
function obChg(obj, act, sml, lrg) {
    this.id = obj;
    this.action = act;
    this.lowValue = sml;
    this.highValue = lrg;
}

var userWidth;
var docLoaded = false;
var scrollaExist = false;
var criticalRes = 925;
    // resolution above which large widths are used

if (canGetElem) {
	arChgs = new Array();
	arSel = new Array();
} 

/*  ----- end global declarations -----  */



/*  ----- event handlers -----  */

function doOnLoad() {
    docLoaded = true;
	// initialise scrollamatic for pages that have one
    if (currentPage.substring(0, 15) == "ninews_homepage" || currentPage == "niclassifieds_homepage" || currentPage == "ninews_multimedia") {
		// and flag that a scrollamatic exists
        scrollaExist = true;
        initScrollers();
    }
	doResize();
    randomPaper();
    rotateWeather(0);
}

function doResize() {

    if (docLoaded) {
		// for all pages with a scrollamatic
		if (scrollaExist) {
			updateScrolla();
		}
	    if (currentPage == "niclassifieds_homepage") {
	        setStoryWrap("rightStory12");
	        setStoryWrap("leftStory12");        
	    }
	    if (currentPage == "story") {
	        setImageSize();
	    }
	    setLeftnavLineLength();
	}

}


/*  ----- end event handlers -----  */



/*  ----- document style changes -----  */

/*	common functions  */

function getElementsByClassName(clss, prnt, tg) {
    var elements = new Array();
    tg = tg || '*';
    prnt = prnt || document;
    var list = prnt.getElementsByTagName(tg);
    for (var i = 0; i < list.length; ++i) {
        if (list[i].className == clss) {
            elements.push(list[i]);
        }
    }
	return elements;
}

function findPosY(obj) {
    /* Find Position script by:
       Peter-Paul Koch
       http://www.quirksmode.org */
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
        }
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
    /* end Find Position script */
}


/*  left navigation right border  */

function setLeftnavLineLength() {
    if (canGetElem&&document.getElementById("middleContent")) {
		// find height of middle content or height of right column, whichever is taller
        tmpHeight = Math.max(document.getElementById("middleContent").offsetHeight, document.getElementById("rightnav").offsetHeight);
		if (document.getElementById("leaderboardAd") && (userWidth > criticalRes)) {
            tmpHeight += document.getElementById("leaderboardAd").offsetHeight;
            tmpHeight += 10;
        }
        
		currentLeftNavHeight = document.getElementById("leftnavPrimary").offsetHeight;
		
        // tmpHeight += "px";
		
		// If left nav isn't already taller
		if(tmpHeight > currentLeftNavHeight) {
		    // set height of leftnav to height determined above
            document.getElementById("leftnavPrimary").style.height = tmpHeight+"px";
		}
    }
}


/*  div components  */

function updateDivs() {

	// for each entry in the array of resizing changes required
    for (k in arChgs) {
		// check to see if the element exists on page
        if (document.getElementById(arChgs[k].id)) {
            if (userWidth < criticalRes) {
                tmpTargetVal = arChgs[k].lowValue;
            }
            else {
                tmpTargetVal = arChgs[k].highValue;
            }
            // change the required style
			document.getElementById(arChgs[k].id).style[arChgs[k].action] = tmpTargetVal;
        }
        else {
			// if element isn't found, we might as well delete the entry from the array
            delete arChgs[k];
        }
    }
	   
}


/*  prevent short text wrapping  */

// specify the container containing paragraphs with an image on the left (which the text needs to clear in 800x600)
function setStoryWrap(obj) {
    if (canGetElem) {
    
		// check if the container exists
        if (document.getElementById(obj)) {
            tmpStoryCont = document.getElementById(obj)
			// for each p inside the container
            for (z = 0; z < tmpStoryCont.getElementsByTagName("p").length; z++) {
                if (userWidth < criticalRes) {
					// if 800x600, set to clear left
                    tmpStoryCont.getElementsByTagName("p")[z].style.clear = "left";
                }
                else {
					// if 1024x768, set to not clear
                    tmpStoryCont.getElementsByTagName("p")[z].style.clear = "none";
                }
            }
        }
    
    }
}


/* masthead front page select box */

var paperLink;
var theSelect;



function loadPaperImage(theSelect) {
	pictmp = new Image(126,178);
	pictmp.src = metaPaper[theSelect.value][2];
	document.images["paperPlace"].src = eval("pictmp" + ".src");
	paperLink=metaPaper[theSelect.value][0];
}

function papersLink(dest) {
	ptmp = document.papersDrop.papersDropSelect.options[document.papersDrop.papersDropSelect.selectedIndex];
	if (dest=="site") {
	window.location=paperLink;
	}
	if (dest=="delivery") {
	window.location=metaPaper[ptmp.value][1];
	}
}

function randomPaper() {
	var randomPaper=Math.floor(Math.random()*metaPaper.length) // no. of papers
	document.papersDrop.papersDropSelect.selectedIndex=randomPaper;
	ptmp = document.papersDrop.papersDropSelect.options[document.papersDrop.papersDropSelect.selectedIndex];
	paperLink = ptmp.value;
	loadPaperImage(ptmp);
}

/*  classifieds box  */

function clearTabs() {
    if (canGetElem) {
    
        // clear all blue color tabs during div changes
    	document.getElementById("jobsActive").style.display = "none";
        document.getElementById("carsActive").style.display = "none";
    	document.getElementById("matchActive").style.display = "none";
        
    }
}

function clearDivs() {
    if (canGetElem) {
    
        // clear all divs on page refresh / load
    	document.getElementById("jobs").style.display = "none";
        document.getElementById("cars").style.display = "none";
    	document.getElementById("match").style.display = "none";
        
    }
}
	
function show_div(id) {
    if (canGetElem) {
    
        // show divs and active tab for each section
    	clearDivs();
        document.getElementById(id).style.display = "block";
            // turns on active div content layer
    	clearTabs();
    	document.getElementById(id + "Active").style.display = "block";
            // turns on active tab div layer

    }
}

function get_random() {
    // choose random number between 0 - 2
    var ranNum = Math.round(Math.random()*2);
    return ranNum;
}

function randomDiv() { 
   // choose a random id name for classified tabs.
   var whichDiv = get_random();   
   var div = new Array(3)
   div[0]="jobs";
   div[1]="cars";
   div[2]="match";
   // apply random id name on page refresh   
   show_div((div[whichDiv]));
}
 
function ValidateForm(f)
	{
		if (f.make_id.selectedIndex == 0)
		{
			 alert("You need to specify a make");
			 f.make_id.focus();
			 return false;
		}

		if 	(f.search_type.options[f.search_type.selectedIndex].value == 3)
		{
			f.action="http://search.carsguide.news.com.au/news/search_new_xt.jsp";
		}
		else
		{
			f.action="http://search.carsguide.news.com.au/news/search_used_xt.jsp";		
		}	
		return true;
	}
	
function ChangeType(f)
{
	//Change the values in the make dropdown
	if (f.search_type.options[f.search_type.selectedIndex].value == 1)
	{
		//We have Dealer cars
		//First clear the location dropdown
	    for (i=f.region_id.length-1; i>=0; i--)
	    	f.region_id.options[i] = null
		//Now fill it with the correct value	
	    f.region_id.options[0] = new Option("Any Location","Any Location")
	    f.region_id.options[1] = new Option("ACT","ACT")
	    f.region_id.options[2] = new Option("NSW","NSW")
	    f.region_id.options[3] = new Option("QLD","QLD")
	    f.region_id.options[4] = new Option("SA","SA")
	    f.region_id.options[5] = new Option("TAS","TAS")
	    f.region_id.options[6] = new Option("VIC","VIC")
	    f.region_id.options[7] = new Option("WA","WA")										
	}
	else
	{
		//We have Classified cars	
		//First clear the location dropdown
	    for (i=f.region_id.length-1; i>=0; i--)
	    	f.region_id.options[i] = null
		//Now fill it with the correct value	
	    f.region_id.options[0] = new Option("Any Location","Any Location")
	    f.region_id.options[1] = new Option("Adelaide", "Adelaide")
	    f.region_id.options[2] = new Option("Brisbane","Brisbane")		
	    f.region_id.options[3] = new Option("Cairns","Cairns")		
	    f.region_id.options[4] = new Option("Charters Towers (Qld)","Charters Towers (Qld)")		
	    f.region_id.options[5] = new Option("Darwin","Darwin")		
	    f.region_id.options[6] = new Option("Gold Coast (Qld)","Gold Coast (Qld)")		
	    f.region_id.options[7] = new Option("Hobart","Hobart")		
	    f.region_id.options[8] = new Option("Melbourne","Melbourne")		
	    f.region_id.options[9] = new Option("Perth","Perth")		
	    f.region_id.options[10] = new Option("Sydney","Sydney")		
	    f.region_id.options[11] = new Option("Townsville","Townsville")		
	}

}

function validateC1(thef) {
	if (thef.q.value=="Keywords") {
		thef.q.value = "";
	}
	if (thef.qCity.value=="City or suburb") {
		thef.qCity.value = "";
	}	
}


/*  ----- end document style changes -----  */



/*  ----- external resources -----  */

/*  etrade stock price form code  */

function displayProductSearch() {
	newwindow = window.open("https://www.etradeaustralia.com.au/Application/ProductSearch/ProductSearch.asp", "ProductSearch", "dependent=no,height=350px,width=320px,scrollbars,resizable=yes,alwaysRaised=yes");
}
	
function doQuote() {
	var strURL;
	var strSymbol = escape(window.document.frmStockQuote.Code.value);
	var strExchange = window.document.frmStockQuote.Exchange[document.frmStockQuote.Exchange.selectedIndex].value;
	var strType = window.document.frmStockQuote.Type[document.frmStockQuote.Type.selectedIndex].value;
	strURL = "https://www.etradeaustralia.com.au/Products/StockCentre/StockCentre.asp?DisplayAs=Quotes&Code=" + strSymbol + "&Exchange=" + strExchange + "&Type=" + strType;
	document.frmStockQuote.URL.value = strURL;
	return true;
}


// weather 

function setWeather(theoption) {
	if (theoption.options[theoption.selectedIndex].value == "more") {
		return false;
	}
	else {
		clearTimeout(wTime);
		tt="na";
		theplace = eval("w"+theoption.options[theoption.selectedIndex].value);
		updateWeatherDiv(theplace);
	}
}

var tts=0;
var wTime;
var tt="timer";

function rotateWeather(stateNum) {
	if (navigator.appName.indexOf("Microsoft") == -1) {
		ranNumba=(wStates.length-1);
		stateNum=Math.floor(Math.random()*ranNumba)
	}	
	if (tt=="timer") {
		stateNumx = wStates[stateNum];
		stateNumxy = eval(stateNumx);
		updateWeatherDiv(stateNumxy);
	}
}

function updateWeatherDiv(tp) {
	// city 
	document.getElementById("weatherCity").firstChild.nodeValue = tp[0];
	// forecast 
	document.getElementById("weatherForecast").firstChild.nodeValue = tp[2];	
	// hi low
	document.getElementById("weatherHiLow").firstChild.nodeValue = tp[4] +" - "+ tp[3];
	// image
	document.getElementById("weatherIcon").src = tp[1];
	if ((tt=="timer")&&(navigator.appName.indexOf("Microsoft") != -1)) {
		if (tts<(wStates.length-1)) {
			tts++;
		} else {
			tts=0;
		}	
		var wTime = setTimeout("rotateWeather(tts)",3200);
	} 
}

    
/*  ----- external resources -----  */




/*  ----- end dropdown contructor -----  */

// cookies
function getCookieVal(offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1)
	endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

function FixCookieDate(date) {
	var base = new Date(0);
	var skew = base.getTime();
	if (skew > 0) 
		date.setTime (date.getTime() - skew);
}

function GetCookie(name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i=0;
	while (i < clen) {	
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg)
		return getCookieVal (j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;
		}
	return null;
}

function SetCookie(name,value,expires,path,domain,secure) {
	document.cookie = name + "=" + escape (value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
}

// end cookies

/*  end NEWS SUBSET COMMON script  */

/* pull stock quote form data and append to url */
function goStockUrl() {
	var quoteID = document.getElementById('quote').value;
	window.location.href = "http://markets.news.com.au/newscorp/entry.aspx?secid=" + quoteID;
}
