//vers 0.25 - the current lang selection is taken from navi_controller
//vers 0.26 - the current lang selection is taken from navi_controller and initialization is done in the end of file and NOT from onload() method


function fnItemToggle(fnToggleItem) {
	while ( fnToggleItem.parentNode ) {
		if(fnToggleItem.parentNode.className == 'fnClosed') {
			fnToggleItem.parentNode.className = 'fnOpen';
			return { elem: fnToggleItem.parentNode, status: 1 };
		}else if(fnToggleItem.parentNode.className == 'fnOpen'){
			fnToggleItem.parentNode.className = 'fnClosed';
			return { elem: fnToggleItem.parentNode, status: 0 };
		}
		fnToggleItem = fnToggleItem.parentNode;
	}
	return null;
}

function traverseChildren(elem, filter, action) {
	if (elem.nodeType != 1) {
		return;
	}
	for ( var i=0, len = elem.childNodes.length; i<len; ++i) {
		var child = elem.childNodes[i];
		if (filter != null && filter(child)) continue;
		var ret = action(child);
		if (ret) return ret;
	}
	return false;
}

function notElementFunc(name) {
	return function(item) {return item.nodeType != 1 || item.tagName.toLowerCase() != name;}
}

function fnBoxSwap(fnNewActive) {
	var fnFindParent = fnNewActive;
	var fnSwapperBox = '', fnSwapperNav = '', fnSwapperNavItem = '', fnSwapperContent = '';
	var pos = -1, count = -1;
	
	//Find Nav and Container
	while ( fnFindParent.parentNode ) {
		fnFindParent = fnFindParent.parentNode;
		if ( fnFindParent.tagName.toLowerCase() == "ul" ) fnSwapperNav = fnFindParent;
		if ( fnFindParent.className == "fnSwapBox" ) fnSwapperBox = fnFindParent;
		if ( fnSwapperBox !== '' && fnSwapperNav !== '' ) break;
	}
	
	/* Find the position of the clicked list item. Mark it active and
	   all other items inactive. */
	traverseChildren(fnSwapperNav,
					 notElementFunc('li'),
					 function(item) {
						 count++;
						 if (item == fnNewActive) {
							 pos = count;
							 item.className = 'fnNavActive';
						 } else {
							 item.className = '';
						 }
						 return false;
					 });
	
	if (pos == -1) {
		return;
	}

	/* Find the div containing the content divs */
	traverseChildren(fnSwapperBox,
					 notElementFunc('div'),
					 function(item) {
						if (item.className == 'fnContentContainer') {
							fnSwapperContent = item;
							return true;
						}
					 });
	
	if (fnSwapperContent == '') {
		return;
	}
	
	/* Find the right content div based on the position of the clicked list item. Mark
	   that as opened and all other as closed. */
	count = -1;
	traverseChildren(fnSwapperContent,
					 notElementFunc('div'),
					 function(item) {
						count++;
					 	if (count == pos) {
							item.className = 'fnOpen';
						} else if (item.className == 'fnOpen') {
							item.className = 'fnClosed';
						}
						return false;
					 });
	return false;
}

function selectCalendarMonth(id) {
	var wrapper = document.getElementById('calendarWrapper');
	traverseChildren(wrapper, null, 
	                 function(elem) {
					   if (elem.id != id) {
					     elem.className = 'hidden';
					   } else {
					     elem.className = '';
					   }
					   return null;
					 });
	return false;	
}


//Select Box Replacement
function selectReplacement(obj) {
	// append a class to the select
	obj.className += ' replaced';
	// create list for styling
	var ul = document.createElement('ul');
	ul.className = 'selectReplacement';
	var opts = obj.options;

    if (false) { //SRG commented out, this taken from navi_controller, not from DOM
        var selectedOpt;
        for (var i = 0; i < opts.length; i++) {
            if (opts[i].selected) {
                selectedOpt = i;
                break;
            } else {
                selectedOpt = 0;
            }
        }
    }
    
    for (var i=0; i<opts.length; i++) {
		var li = document.createElement('li');
		var txt = document.createTextNode(opts[i].text);
		li.appendChild(txt);
		li.selIndex = opts[i].index;
		li.selectID = obj.id;
		li.onclick = function() {
			selectMe(this);
		}
		//if (i == selectedOpt) { //SRG commented out, this taken from navi_controller, not from DOM
		if (i == navi_controller_instance.CURR_LANG_IDX) {
			li.className = 'selected';
			li.onclick = function() {
				this.parentNode.className += ' selectOpen';
				this.onclick = function() {
					selectMe(this);
				}
			}
		}
		if (window.attachEvent) {
			li.onmouseover = function() {
				this.className += ' hover';
			}
			li.onmouseout = function() {
				this.className = 
				this.className.replace(new RegExp(" hover\\b"), '');
			}
		}
		ul.appendChild(li);
	}
	// add the input and the ul
	obj.parentNode.appendChild(ul);
}
function selectMe(obj) {
	var lis = obj.parentNode.getElementsByTagName('li');
	for (var i=0; i<lis.length; i++) {
		if (lis[i] != obj) { // not the selected list item
			lis[i].className='';
			lis[i].onclick = function() {
				selectMe(this);
			}
		} else {
			setVal(obj.selectID, obj.selIndex);
            navi_controller_instance.change_language(null,obj.selIndex);
			obj.className='selected';
			obj.parentNode.className = 
			obj.parentNode.className.replace(new RegExp(" selectOpen\\b"), '');
			obj.onclick = function() {
				obj.parentNode.className += ' selectOpen';
				this.onclick = function() {
					selectMe(this);
				}
			}
		}
	}
}
function setVal(objID, selIndex) {
	var obj = document.getElementById(objID);
	obj.selectedIndex = selIndex;
}
function setForm() {
	if (document.getElementById('fnLanguageSelect')) {
		selectReplacement(document.getElementById('fnLanguageSelect'));
	}
}
function closeSel(obj) {
// close the ul
}

//INIT FUNCTION (originally was defined in ONLOAD )
function scripts_init() { 
	(document.all && !window.print) ? null : setForm();
}


/* BOOKMARK THIS PAGE */
function ehref() { return encodeURIComponent(location.href); }
function etitle() { return encodeURIComponent(document.title); }
function bookmarkDelicious() {
	window.open('http://delicious.com/save?v=5&noui=&jump=close&url='+ehref()+'&title='+etitle(),'delicious','toolbar=no,width=550,height=550,resizable=yes');
	return false;
}
function bookmarkDigg() {
	window.open('http://digg.com/submit?url='+ehref()+'&title='+etitle()+'&bodytext=&media=news&topic=tech_news','digg','toolbar=no,width=1070,height=750,scrollbars=yes,resizable=yes');
	return false;
}
function bookmarkGoogle() {
	window.open('http://www.google.com/bookmarks/mark?op=add&hl=en&bkmk='+ehref()+'&title='+etitle(),'google','toolbar=no,width=650,height=600,resizable=yes');
	return false;
}
function bookmarkYahoo() {
	window.open('http://myweb2.search.yahoo.com/myresults/bookmarklet?u='+ehref()+'&t='+etitle(),'yahoo','toolbar=no,width=600,height=650,scrollbars=yes,resizable=yes');
	return false;
}
function bookmarkStumbleUpon() {
	window.open('http://www.stumbleupon.com/submit?url='+ehref()+'&title='+etitle(),'stumbleupon','toolbar=no,width=1070,height=550,scrollbars=yes,resizable=yes');
	return false;
}
function bookmarkReddit() {
	window.open('http://www.reddit.com/submit?url='+ehref()+'&title='+etitle(),'reddit','toolbar=no,width=650,height=650,resizable=yes');
	return false;
}
function bookmarkFurl() {
	window.open('http://www.furl.net/storeIt.jsp?u='+ehref()+'&t='+etitle(),'furl','toolbar=no,width=600,height=750,scrollbars=yes,resizable=yes');
	return false;
}
function bookmarkTechnorati() {
	window.open('http://technorati.com/faves?add='+ehref(),'technorati','toolbar=no,width=1000,height=750,scrollbars=yes,resizable=yes');
	return false;
}
function bookmarkNewsvine() {
	window.open('http://www.newsvine.com/_tools/seed&save?u='+ehref()+'&h='+etitle(),'newsvine','toolbar=no,width=970,height=750,resizable=yes');
	return false;
}
function bookmarkMagnolia() {
	window.open('http://ma.gnolia.com/bookmarklet/add?url='+ehref()+'&title='+etitle()+'&description=','magnolia','toolbar=no,width=800,height=600,scrollbars=yes,resizable=yes');
	return false;
}
function bookmarkSquidoo() {
	window.open('http://www.squidoo.com/lensmaster/bookmark?'+ehref(),'squidoo','toolbar=no,width=750,height=600,scrollbars=yes,resizable=yes');
	return false;
}
function bookmarkTwitter() {
	window.open('http://twitter.com/home?status=Add+This:+'+ehref(),'twitter','toolbar=no,width=790,height=550,resizable=yes');
	return false;
}
function bookmarkFacebook() {
	window.open('http://www.facebook.com/sharer.php?u='+ehref()+'&t='+etitle(),'facebook','toolbar=no,width=550,height=550,resizable=yes');
	return false;
}

/* SHARE THIS PAGE */
function shareThisPage() {
	window.open('https://sandbox.forum.nokia.com/dynamic/send_this_page.html?pageurl='+document.location,'share_this_page','scrollbars=no,resizable=no,width=480,height=480,resizable=yes');
	return false;
}

/* DOWNLOAD MANAGER */
// download of multiple file (tool page)
function getDLMethod() {
	var parameter = document.version.fileId.options[document.version.fileId.selectedIndex].value;
	var split = parameter.lastIndexOf('*');
	var fileName = parameter.substring(split+1, parameter.length);
	var path = parameter.substring(0, split);
	var DLMethod = "a";
	if(document.version.downloadMethod[0].checked) { DLMethod = "s"; }
	if(DLMethod == "a") { startdm(path, fileName); } else { document.location = path; }
}

// download with download manager (tool page)
function startdm(uri, fileName) {
	var now = new Date();
	var windowName = now.getFullYear() + "" + now.getMonth() + "" + now.getDate() + "" + now.getHours() + "" + now.getMinutes() + "" + now.getSeconds();
	var url="/dynamic/download_manager.html?url=" + uri + "&filename=" + fileName;
	window.open(url,windowName,"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width=420,height=330");
}
/* END OF DOWNLOAD MANAGER */

// Generic pop up window open function.
function MM_openBrWindow(theURL,winName,features) { //v2.0
	window.open(theURL,winName,features);
}
                                 

//INITIALIZATION
scripts_init();

function validateForm(thisform) {
					name= thisform.name;
					if (name == 'UPTml29034') {
                                                var isRegionUnvalid = validateRegion(thisform);
                                                if (isRegionUnvalid == true)
                                                        return isRegionUnvalid;
					}
					if (emailCheck2(thisform.email.value)) {		
						return false;
					} else {
						return true;
					}	
					
				}
				
				function validateRegion(thisform) {
					if((thisform.val_15527.checked == false)&&(thisform.val_15528.checked == false)&&(thisform.val_15529.checked == false)) {
						alert("Please select geographic areas are you interested in");
						return(true);
					}
				}
				
				function emailCheck2 (emailStr) 
					{
						var emailPat=/^(.+)@(.+)$/;
						var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
						var validChars="\[^\\s" + specialChars + "]";
						var quotedUser="(\"[^\"]*\")";
						var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
						var atom=validChars + '+';
						var word="(" + atom + "|" + quotedUser + ")";
						var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
						var domainPat=new RegExp("^" + atom + "(\." + atom +")*$");
						var matchArray=emailStr.match(emailPat);
						
						if (matchArray==null) {
							alert("Email address seems incorrect (check @ and .'s)");
							return false;
						}
						
						var user=matchArray[1];
						var domain=matchArray[2];
						
						if (user.match(userPat)==null) {
							alert("The username doesn't seem to be valid.");
							return false;
						}
						
						var IPArray=domain.match(ipDomainPat);
						
						if (IPArray!=null) {
							  for (var i=1;i<=4;i++) {
								if (IPArray[i]>255) {
									alert("Destination IP address is invalid!");
								return false;
								}
							}
							return true;
						}
						
						var domainArray=domain.match(domainPat);
						
						if (domainArray==null) {
							alert("The domain name doesn't seem to be valid.");
							return false;
						}
						
						var atomPat=new RegExp(atom,"g");
						var domArr=domain.match(atomPat);
						var len=domArr.length;
						
						if (domArr[domArr.length-1].length<2 || 
							domArr[domArr.length-1].length>4) {
						   alert("The address must end in a three or four-letter domain, or two letter country.");
						   return false;
						}
						
						if (len<2) {
						   var errStr="This address is missing a hostname!";
						   alert(errStr);
						   return false;
						}
						return true;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


function MultiValueCookie(name) {
	var value = readCookie(name);
	this.name = name;
	this.values = new Array();
	if (value != null) {
		var items = value.split(",");
		for (var i=0;i<items.length;i++) {
			var parts = items[i].split("|");
			if (parts.length == 2) {
				this.values[this.values.length] = { key: parts[0], value: parts[1] };	
			}
		}
	}
}

MultiValueCookie.prototype = {
	findValueIndex: function(keyStr) {
		for (i=0; i<this.values.length;i++) {
			if (this.values[i].key == keyStr) {
				return i;
			}
		}
		return -1;
	},
	
	setValue: function(keyStr, str) {
		var i = this.findValueIndex(keyStr);
		var newStr;
		if (i == -1) {
			i = this.values.length;
			newStr = str;
		} else {
			if (this.values[i].value == '') {
				newStr = str;
			} else {
				var re=new RegExp("("+str+" )|("+str+"$)");
				if (re.exec(this.values[i].value) != null) return;
				newStr = this.values[i].value + " " + str;
			}
		}
	
		this.values[i] = {
			key: keyStr,
			value: newStr
		};
	},
	
	removeValue: function(keyStr, str) {
		var i = this.findValueIndex(keyStr);
		if (i == -1) return;
		var re=new RegExp("("+str+" )|("+str+"$)");
		this.values[i] = {
			key: keyStr,
			value: this.values[i].value.replace(re, "")
		};
	},
	
	getValues: function(keyStr) {
		var i = this.findValueIndex(keyStr);
		if (i == -1) return null;
		return this.values[i].value.split(" ");
	},
	
	save: function() {
		var result = '';
		for (i=0;i<this.values.length;i++) {
			result = result + (this.values[i].key + "|" + this.values[i].value);
			if (i+1 < this.values.length) {
				result += ",";
			}
		}
		createCookie(this.name, result, 1);
	}
};
