/* =v============ INIT ============v= */
// These functions are run at the loading of a page
window.onload = function () {
	// Check if the browser's resolution is smaller than or equal to QVGA
	// If so, generate Mobinav and set mobile stylesheet as active
	if(getScreenSize(240, 320)) {
		generateMobinav();
		setActiveStyleSheet('Mobile');
	}
	createToggleableContent();
	createPopups();
	getRequiredInputLinks();
	parseSearchString();
	getForms();
	populateFormsFromCookies();
    dynamicSelect("region", "country");
    dynamicSelect("country", "city");
    checkFlash();
    displayScreenSize();
}
/* =^==============================^= */

/* =v=========== MOBINAV ==========v= */
// This function generates a small collection of quick links that are
// constructed based on the document headings and links contained
// in the navigation.

// Set the default Mobinav state to off
var mobinavState = "off";

/* -v------- Fetch Headings -------v- */
// This function fetches multiple elements and returns them in an
// array.
function getElementsByTagNames(list,obj) {
	if (!obj) var obj2 = document;  // leif - original file don't compile in vs2008
	if (obj) obj2 = obj;            // leif
	var tagNames = list.split(',');
	var resultArray = new Array();
	for (var i=0;i<tagNames.length;i++) {
		var tags = obj2.getElementsByTagName(tagNames[i]);
		for (var j=0;j<tags.length;j++) {
			resultArray.push(tags[j]);
		}
	}
	var testNode = resultArray[0];
	if (!testNode) return [];
	if (testNode.sourceIndex) {
		resultArray.sort(function (a,b) {
				return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition) {
		resultArray.sort(function (a,b) {
				return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}
	return resultArray;
}
/* -^------------------------------^- */

/* -v------ Generate Mobinav ------v- */
// This function generates the mobinav and places it into the document
function generateMobinav() {
	if(document.getElementById && document.getElementsByName) {
		// Create the container div for all elements inside the Mobinav
		var mobinav = document.createElement('div');
		mobinav.id = 'mobinav';
		// Create the Mobinav icon and link
		var mobinavLink = document.createElement('a');
		mobinavLink.href = "#";
		mobinavLink.onclick = toggleMobinav;
		mobinavLink.innerHTML = "Mobinav";
		mobinavLink.style.margin = "0 0 0 1px";
		mobinavLink.id = "mobinavToggleLink";
		mobinav.appendChild(mobinavLink);
		// Create the containing div
		var base = document.createElement('div');
		base.id = "mobinavContent";
		var headings = getElementsByTagNames('h2,h3,h4,h5');
		// Generate quick links based on navigation
		var links = document.getElementById('navigation').getElementsByTagName('a');
		var linkList = document.createElement('ol');
		linkList.className = "navList";
		// Go through the navigation links and generate corresponding links
		var linkEntry;                      // leif - original file don't compile in vs2008
		var link;                           // leif - original file don't compile in vs2008
		for(i = 0; i < links.length; i++) {
			linkEntry = document.createElement('li');                     // leif - original file don't compile in vs2008
			linkEntry.className = "navLink";
			link = document.createElement('a');                      // leif - original file don't compile in vs2008
			link.innerHTML = links[i].innerHTML;
			link.href = links[i].href;
			linkEntry.appendChild(link);
			linkList.appendChild(linkEntry);
		}	
		// Generate table of contents based on document headings
		var linkList2 = document.createElement('ol');
		linkList2.className = "mobinavList";
		// Go through the headings and generate corresponding links
		for(i = 0; i < headings.length; i++) {
				linkEntry = document.createElement('li');                     // leif - original file don't compile in vs2008
				linkEntry.className = "mobinavLink";
				link = document.createElement('a');                      // leif - original file don't compile in vs2008
				link.innerHTML = headings[i].innerHTML;
				linkEntry.appendChild(link);
				linkList2.appendChild(linkEntry);
			var headerId = headings[i].id || 'link' + i;
			link.href = '#' + headerId;
			link.onclick = toggleMobinav;
			headings[i].id = headerId;
		}
		// Append the link lists to the containing div
		base.appendChild(linkList);
		base.appendChild(linkList2);
		mobinav.appendChild(base);
		// Append the containing div to body
		document.getElementsByTagName('body')[0].appendChild(mobinav);
	}
}
/* -^------------------------------^- */

/* -v------- Toggle Mobinav -------v- */
// This function shows and hides the Mobinav based on the state
function toggleMobinav() {
	if(mobinavState == "on") {
		document.getElementById("mobinavContent").style.display = "none";
		mobinavState = "off";
	} else {
		document.getElementById("mobinavContent").style.display = "block";
		mobinavState = "on";
	}
}
/* -^------------------------------^- */
/* =^==============================^= */

/* =v==== STYLESHEET SWITCHER =====v= */
function setActiveStyleSheet(title) {
	if(document.getElementsByTagName) {
		var i, a, main;
//		for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		for(i=0; i<20; i++) {
		    if (document.getElementsByTagName("link")[i])
		    {
		        a = document.getElementsByTagName("link")[i];
			    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
				    a.disabled = true;
				    if(a.getAttribute("title") == title) a.disabled = false;
			    }
			}
		}
	}
	return false;
}
/* =^==============================^= */

/* =v==== SCREEN SIZE SNIFFER =====v= */
// General function that handles details about the client's screen.
function getScreenSize(minWidth, minHeight) {
	if(screen && minWidth && minHeight) {
		if(screen.width > minWidth && screen.height > minHeight) return false;
		else return true;
	} 
	else return false;
}
/* =^==============================^= */

/* =v======== FORM COOKIES ========v= */
/* -v Get forms + generate cookies v- */
// This function fetches all forms that contain the class "cache"
// from the document and adds corresponding events to form objects
// that will generate cookies holding the form element's information
function getForms() {
	var formCollection = document.forms;
	for(var i = 0; i < formCollection.length; i++) {
		if(formCollection[i].className.match("cache")) {
			var elementCollection = formCollection[i].elements;
			expire = 30;
			var expireDate = new Date();
			expireDate.setDate(expireDate.getDate()+expire);
			for(var j = 0; j < elementCollection.length; j++) {
				if(elementCollection[j].type == "text" || elementCollection[j].type == "select-one" || elementCollection[j].type == "textarea") {
					elementCollection[j].onchange = function() {
						document.cookie = escape(this.id) + "=" + escape(this.value) + ((expire==null) ? "" : "; expires=" + expireDate.toGMTString());
					}
				} else if(elementCollection[j].type == "radio") {
					elementCollection[j].onclick = function() {
						document.cookie = escape(this.name) + "=" + escape(this.id) + ((expire==null) ? "" : "; expires=" + expireDate.toGMTString());
					}
				} else if(elementCollection[j].type == "checkbox") {
					elementCollection[j].onclick = function() {
						document.cookie = escape(this.id) + "=" + escape(this.checked) + ((expire==null) ? "" : "; expires=" + expireDate.toGMTString());
					}					
				}
			}
		}
	}
}
/* -^------------------------------^- */

/* -v---- Populate form fields ----v- */
// This function reads the cookies set for the site the document relies in
// and then populates the corresponding form elements with them
function populateFormsFromCookies() {
	if(document.getElementById && document.getElementsByName) {
		if(document.cookie.length > 0) {
			var cookieArray = new Array();
			cookieArray = document.cookie.split(";");
			for(var i = 0; i < cookieArray.length; i++) {
				var cookieValueStart = cookieArray[i].indexOf("=");
				var cookieValue = unescape(cookieArray[i].substring(cookieValueStart + 1, cookieArray[i].length));
				var cookieId;       // leif - original file don't compile in VS2008
				if(cookieArray[i].charAt(0)==' ') cookieId = unescape(cookieArray[i].substring(1, cookieValueStart));       // leif - original file don't compile in VS2008
				else cookieId = unescape(cookieArray[i].substring(0, cookieValueStart));       // leif - original file don't compile in VS2008
				// First populate the text fields, checkboxes and selects
				if(document.getElementById(cookieId)) {
					if(document.getElementById(cookieId).type == "checkbox") {
						if(cookieValue == "true")	document.getElementById(cookieId).checked = true;
						if(cookieValue == "false") document.getElementById(cookieId).checked = false;
					} else if(document.getElementById(cookieId).type == "text" || document.getElementById(cookieId).type == "select-one" || document.getElementById(cookieId).type == "textarea") document.getElementById(cookieId).value = cookieValue;
				}
				// The same for radio buttons
				if(document.getElementsByName(cookieId)) {
					var radioArray = document.getElementsByName(cookieId);
					for(var j = 0; j < radioArray.length; j++) {
						if(radioArray[j].id == cookieValue) radioArray[j].checked = true;
					}
				}
			}
		}
	}
}
/* -^------------------------------^- */
/* =^==============================^= */

/* =v========= FORM CHECK =========v= */
// This is a simple function for demonstrating active
// form input checking. In real applications one should
// use more elaborate checking.
/* -v----- Fetch input links ------v- */
// This function fetches all input elements and adds an event
// to elements with the class 'checkInput'.
function getRequiredInputLinks() {
	var inputCollection = document.getElementsByTagName('input');
	for(var i = 0; i < inputCollection.length; i++) {
		if(inputCollection[i].className.match("checkInput")) {
			inputCollection[i].onblur = function() {
				checkFormInput(this);
			}
		}
	}
}
/* -^------------------------------^- */

/* -v-------- Check input ---------v- */
// This function checks if the user has input any information.
// If not, the function changes the element's class to invoke
// the user to add the required information.
function checkFormInput(element) {
	if(!element.value) {
		element.className = "error";
	} else {
		element.className = "";
	}
}
/* -^------------------------------^- */
/* =^==============================^= */

/* =v===== DYNAMIC DROP-DOWNS =====v= */
// This function links two drop-downs. It generates a copy of the second drop-down
// and strips its content according to the selection made at the first drop-down.
/* -v------ Link drop-downs -------v- */
function dynamicSelect(id1, id2) {
if (document.getElementById && document.getElementsByTagName && document.getElementById(id1) && document.getElementById(id2)) {
	var sel1 = document.getElementById(id1);
	var sel2 = document.getElementById(id2);
	var clone = sel2.cloneNode(true);
	var clonedOptions = clone.getElementsByTagName("option");
	refreshDynamicSelectOptions(sel1, sel2, clonedOptions);
	sel1.onchange = function() {
		refreshDynamicSelectOptions(sel1, sel2, clonedOptions);
		}
	}
}
/* -^------------------------------^- */

/* -v------- Strip options --------v- */
function refreshDynamicSelectOptions(sel1, sel2, clonedOptions) {
	while (sel2.options.length) {
		sel2.remove(0);
	}
	var pattern1 = /( |^)(select)( |$)/;
	var pattern2 = new RegExp("( |^)(" +
	sel1.options[sel1.selectedIndex].value + ")( |$)");
	for (var i = 0; i < clonedOptions.length; i++) {
		if (clonedOptions[i].className.match(pattern1) || clonedOptions[i].className.match(pattern2)) {
			sel2.appendChild(clonedOptions[i].cloneNode(true));
		}
	}
}
/* -^------------------------------^- */
/* =^==============================^= */

/* =v===== TOGGLEABLE CONTENT =====v= */
// This is a function for toggling content's visibility.
function createToggleableContent() {
	// First fetch all links
	var linkCollection = document.links;
	for(var i = 0; i < linkCollection.length; i++) {
		// If link's class contains 'toggleable' then toggle the previous element's
		// visibility based on its display property
		if(linkCollection[i].className.match("toggleable")) {
			linkCollection[i].onclick = function() {
				if(this.previousSibling.className.match("hidden")) {
					this.innerHTML = "Hide";
					this.previousSibling.className = "";
					this.previousSibling.style.display = "block";
				} else {
					this.innerHTML = "Read more";
					this.previousSibling.className = "hidden";
					this.previousSibling.style.display = "none";
				}
				return false;
			}
		}
	}
}
/* =^==============================^= */

/* =v===== PARSE SEARCH STRING ====v= */
// This is a small function for parsing the search string
// from the URL. Used only for demonstration purposes.
function parseSearchString() {
	if(document.getElementById("searchResult")) {
		firstVariable = location.search.indexOf("=") + 1;
		document.getElementById("searchResult").innerHTML = location.search.substring(firstVariable);
	}
}
/* =^==============================^= */

/* =v========== POPUPS ============v= */
// This function fetches all anchor tags from the document into an array and adds target="_blank" to every link with the rel value "external"
function createPopups() {
	// Check, if the required DOM method is available
	if(document.getElementsByTagName) {
		// Create the array
		var links = document.getElementsByTagName("a");
		// Go through the array and add target="_blank" when needed
		for(var i = 0; i < links.length; i++) {
			if(links[i].getAttribute("rel") == "external") {
				links[i].target = "_blank";
			}
		}
	}
}
/* =^==============================^= */

/* =v======== FLASH CHECK =========v= */
// This function checks if the device's platform is Series60. If so, the function checks, if Flash Lite is supported. If Flash Lite is supported, the desktop Flash is replaced with corresponding Flash Lite execution. If Flash Lite is not supported, the desktop Flash is replaced with a picture instead.
function checkFlash() {
	if(navigator.platform && navigator.plugins && document.getElementById("flash")) {
		if(navigator.platform == "Series60") {
			for(var i = 0; i < navigator.plugins.length; i++) {
				if(navigator.plugins[i].name == "FLASHLITE") {
					var flashEnabled = true;
					break;
				}
			}
			if(flashEnabled) {
				document.getElementById("flash").innerHTML = "<object type='application/x-shockwave-flash' data='flash/ad_skyscraper_lite.swf' width='120' height='600'><param name='movie' value='flash/ad_skyscraper_lite.swf' /><img src='flash/placeholder.jpg' alt='Picture of Nokia N77' /></object>";
			} else {
				document.getElementById("flash").innerHTML = "<a href='http://europe.nokia.com/phones/n77'><img src='flash/placeholder.jpg' alt='Picture of Nokia N77' /></a>";
			}
		}
	}
}
/* =^==============================^= */

/* =v======== Screen size display =========v= */
function displayScreenSize()
{
	if(document.getElementById("footer")) {
	    document.getElementById("footer").appendChild(document.createTextNode(screen.width + "," + screen.height));
	}
}
/* =^==============================^= */
