
/*
 * Browser check
*/

function Browser() {
	var b=navigator.appName;
	if (b.indexOf('Netscape')!=-1) this.b="ns";
	else if ((b=="Opera") || (navigator.userAgent.indexOf("Opera")>0)) this.b = "opera";
	else if (b=="Microsoft Internet Explorer") this.b="ie";
	if (!b) alert('Unidentified browser.\nThis browser is not supported,');
	this.version=navigator.appVersion;
	this.v=parseInt(this.version);
	this.ns=(this.b=="ns" && this.v>=4);
	this.ns4=(this.b=="ns" && this.v==4);
	this.ns6=(this.b=="ns" && this.v==5);
	this.ie=(this.b=="ie" && this.v>=4);
	this.ie4=(this.version.indexOf('MSIE 4')>0);
	this.ie5=(this.version.indexOf('MSIE 5')>0);
	this.ie55=(this.version.indexOf('MSIE 5.5')>0);
	this.ie6=(this.version.indexOf('MSIE 6.0')>0);
	this.opera=(this.b=="opera");
	this.gecko  = (navigator.product == "Gecko");
	this.dom=(document.createElement && document.appendChild && document.getElementsByTagName)?true:false;
	this.def=(this.ie||this.dom); // most used browsers, for faster if loops
	var ua=navigator.userAgent.toLowerCase();
	if (ua.indexOf("win")>-1) this.platform="win32";
	else if (ua.indexOf("mac")>-1) this.platform="mac";
	else this.platform="other";
}
is=new Browser();

/*
 * IE emulator objects
*/

function emulateAllModel() {
	var allGetter = function () {
		var a = this.getElementsByTagName("*");
		var node = this;
		a.tags = function (sTagName) {
			return node.getElementsByTagName(sTagName);
		};
		return a;
	};
	HTMLDocument.prototype.__defineGetter__("all", allGetter);
	HTMLElement.prototype.__defineGetter__("all", allGetter);
}

function emulateHTMLModel() {

	// This function is used to generate a html string for the text properties/methods
	// It replaces '\n' with "<BR"> as well as fixes consecutive white spaces
	// It also repalaces some special characters	
	function convertTextToHTML(s) {
		s = s.replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\n/g, "<BR>");
		while (/\s\s/.test(s))
			s = s.replace(/\s\s/, "&nbsp; ");
		return s.replace(/\s/g, " ");
	}

	HTMLElement.prototype.insertAdjacentHTML = function (sWhere, sHTML) {
		var df;	// : DocumentFragment
		var r = this.ownerDocument.createRange();
		
		switch (String(sWhere).toLowerCase()) {
			case "beforebegin":
				r.setStartBefore(this);
				df = r.createContextualFragment(sHTML);
				this.parentNode.insertBefore(df, this);
				break;
				
			case "afterbegin":
				r.selectNodeContents(this);
				r.collapse(true);
				df = r.createContextualFragment(sHTML);
				this.insertBefore(df, this.firstChild);
				break;
				
			case "beforeend":
				r.selectNodeContents(this);
				r.collapse(false);
				df = r.createContextualFragment(sHTML);
				this.appendChild(df);
				break;
				
			case "afterend":
				r.setStartAfter(this);
				df = r.createContextualFragment(sHTML);
				this.parentNode.insertBefore(df, this.nextSibling);
				break;
		}	
	};

	HTMLElement.prototype.__defineSetter__("outerHTML", function (sHTML) {
	   var r = this.ownerDocument.createRange();
	   r.setStartBefore(this);
	   var df = r.createContextualFragment(sHTML);
	   this.parentNode.replaceChild(df, this);
	   
	   return sHTML;
	});

	HTMLElement.prototype.__defineGetter__("canHaveChildren", function () {
		switch (this.tagName) {
			case "AREA":
			case "BASE":
			case "BASEFONT":
			case "COL":
			case "FRAME":
			case "HR":
			case "IMG":
			case "BR":
			case "INPUT":
			case "ISINDEX":
			case "LINK":
			case "META":
			case "PARAM":
				return false;
		}
		return true;
	});

	HTMLElement.prototype.__defineGetter__("outerHTML", function () {
		var attr, attrs = this.attributes;
		var str = "<" + this.tagName;
		for (var i = 0; i < attrs.length; i++) {
			attr = attrs[i];
			if (attr.specified)
				str += " " + attr.name + '="' + attr.value + '"';
		}
		if (!this.canHaveChildren)
			return str + ">";
		
		return str + ">" + this.innerHTML + "</" + this.tagName + ">";
	});


	HTMLElement.prototype.__defineSetter__("innerText", function (sText) {
		this.innerHTML = convertTextToHTML(sText);
		return sText;		
	});

	var tmpGet;
	HTMLElement.prototype.__defineGetter__("innerText", tmpGet = function () {
		var r = this.ownerDocument.createRange();
		r.selectNodeContents(this);
		return r.toString();
	});

	HTMLElement.prototype.__defineSetter__("outerText", function (sText) {
		this.outerHTML = convertTextToHTML(sText);
		return sText;
	});
	HTMLElement.prototype.__defineGetter__("outerText", tmpGet);

	HTMLElement.prototype.insertAdjacentText = function (sWhere, sText) {
		this.insertAdjacentHTML(sWhere, convertTextToHTML(sText));
	};

}

/*
 * Init Emulator objects
*/

if (is.gecko) emulateAllModel();
if (is.gecko) emulateHTMLModel();

// See on vaja 
var variableFromEditRubriik_id='';

function zoomTo(width,height,Page) {

    if (document.all) {

	//if (Page!=''){this.location.href=Page};

	var newTop = (screen.width-width)/2
	var newLeft = (screen.height-height)/2

	window.moveTo(newTop,newLeft)
	window.resizeTo(width,height)
    }
}

//---------------------------------------------------------
//                      window opening functions
//---------------------------------------------------------

function avapopup(mypage, myname, w, h, scroll) {
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',notresizable'
	win = window.open(mypage, myname, winprops)
	if (win.opener == null) { win.opener = self }
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}

function avaaken(link, x, y, nimi) {
	var winl = (screen.width - x) / 2;
	var wint = (screen.height - y) / 2;
	editWindow = window.open(link, nimi,'width='+x+',height='+y+',top='+wint+',left='+winl+',toolbar=0,directories=0,menubar=0,status=0,resizable=1,location=0,scrollbars=yes,copyhistory=0');
	if (editWindow.opener == null) { editWindow.opener = self }
}

function avaaken2(link, x, y, doScroll) {
	var winl = (screen.width-x)/2;
	var wint = (screen.height-y)/2;

	var scr = (doScroll)? 'yes' : 'no'

	var newWin = window.open(link, 'Fail','width='+x+',height='+y+',toolbar=0,directories=0,menubar=0,status=0,resizable=1,location=0,scrollbars=' + scr + ',copyhistory=0,left=' + winl + ',top=' + wint);
	newWin.focus();
}
function avaaken3(winname,link, x, y, doScroll) {
	var winl = (screen.width-x)/2;
	var wint = (screen.height-y)/2;

	var scr = (doScroll)? 'yes' : 'no'
	var newWin = window.open(link, winname,'width='+x+',height='+y+',toolbar=0,directories=0,menubar=0,status=0,resizable=1,location=0,scrollbars=' + scr + ',copyhistory=0,left=' + winl + ',top=' + wint);
	newWin.focus();
}

function avaprintaken(link, x, y, nimi, toolbar) {
	var winl = (screen.width - x) / 2;
	var wint = (screen.height - y) / 2;
	editWindow = window.open(link, nimi,'width='+x+',height='+y+',top='+wint+',left='+winl+',toolbar='+toolbar+',directories=0,menubar=1,status=0,resizable=1,location=0,scrollbars=yes,copyhistory=0');
	if (editWindow.opener == null) { editWindow.opener = self }
}

function gallupaken(link, x, y, nimi) {
	var winl = (screen.width - x) / 2;
	var wint = (screen.height - y) / 2;
	editWindow = window.open(link, nimi,'width='+x+',height='+y+',top='+wint+',left='+winl+',toolbar=0,directories=0,menubar=0,status=0,resizable=1,location=0,scrollbars=no,copyhistory=0');
	if (editWindow.opener == null) { editWindow.opener = self }
}

//---------------------------------------------------------
//      dialog window functions (works both in IE and NN)
//---------------------------------------------------------

// Global for brower version branching.
var Nav4 = ((navigator.appName == "Netscape") && (parseInt(navigator.appVersion) == 4))

// One object tracks the current modal dialog opened from this window.
var dialogWin = new Object()

// Generate a modal dialog.
// Parameters:
//    url -- URL of the page/frameset to be loaded into dialog
//    width -- pixel width of the dialog window
//    height -- pixel height of the dialog window
//    returnFunc -- reference to the function (on this page)
//                  that is to act on the data returned from the dialog
//    args -- [optional] any data you need to pass to the dialog
function openDialog(url, width, height, returnFunc, args) {
	if (!dialogWin.win || (dialogWin.win && dialogWin.win.closed)) {
		// Initialize properties of the modal dialog object.
		dialogWin.returnFunc = returnFunc
		dialogWin.returnedValue = ""
		dialogWin.args = args
		dialogWin.url = url
		dialogWin.width = width
		dialogWin.height = height
		// Keep name unique so Navigator doesn't overwrite an existing dialog.
		dialogWin.name = (new Date()).getSeconds().toString()
		// Assemble window attributes and try to center the dialog.
		if (Nav4) {
			// Center on the main window.
			dialogWin.left = window.screenX + 
			   ((window.outerWidth - dialogWin.width) / 2)
			dialogWin.top = window.screenY + 
			   ((window.outerHeight - dialogWin.height) / 2)
			var attr = "screenX=" + dialogWin.left + 
			   ",screenY=" + dialogWin.top + ",resizable=no,width=" + 
			   dialogWin.width + ",height=" + dialogWin.height
		} else {
			// The best we can do is center in screen.
			dialogWin.left = (screen.width - dialogWin.width) / 2
			dialogWin.top = (screen.height - dialogWin.height) / 2
			var attr = "left=" + dialogWin.left + ",top=" + 
			   dialogWin.top + ",resizable=no,width=" + dialogWin.width + 
			   ",height=" + dialogWin.height
		}
		
		// Generate the dialog and make sure it has focus.
		dialogWin.win=window.open(dialogWin.url, dialogWin.name, attr)
		dialogWin.win.focus()
	} else {
		dialogWin.win.focus()
	}
}

// Event handler to inhibit Navigator form element 
// and IE link activity when dialog window is active.
function deadend() {
	if (dialogWin.win && !dialogWin.win.closed) {
		dialogWin.win.focus()
		return false
	}
}

// Since links in IE4 cannot be disabled, preserve 
// IE link onclick event handlers while they're "disabled."
// Restore when re-enabling the main window.
var IELinkClicks

// Disable form elements and links in all frames for IE.
function disableForms() {
	IELinkClicks = new Array()
	for (var h = 0; h < frames.length; h++) {
		for (var i = 0; i < frames[h].document.forms.length; i++) {
			for (var j = 0; j < frames[h].document.forms[i].elements.length; j++) {
				frames[h].document.forms[i].elements[j].disabled = true
			}
		}
		IELinkClicks[h] = new Array()
		for (i = 0; i < frames[h].document.links.length; i++) {
			IELinkClicks[h][i] = frames[h].document.links[i].onclick
			frames[h].document.links[i].onclick = deadend
		}
	}
}

// Restore IE form elements and links to normal behavior.
function enableForms() {
	for (var h = 0; h < frames.length; h++) {
		for (var i = 0; i < frames[h].document.forms.length; i++) {
			for (var j = 0; j < frames[h].document.forms[i].elements.length; j++) {
				frames[h].document.forms[i].elements[j].disabled = false
			}
		}
		for (i = 0; i < frames[h].document.links.length; i++) {
			frames[h].document.links[i].onclick = IELinkClicks[h][i]
		}
	}
}

// Grab all Navigator events that might get through to form
// elements while dialog is open. For IE, disable form elements.
function blockEvents() {
	if (Nav4) {
		window.captureEvents(Event.CLICK | Event.MOUSEDOWN | Event.MOUSEUP | Event.FOCUS)
		window.onclick = deadend
	} else {
		disableForms()
	}
	window.onfocus = checkModal
}
// As dialog closes, restore the main window's original
// event mechanisms.
function unblockEvents() {
	if (Nav4) {
		window.releaseEvents(Event.CLICK | Event.MOUSEDOWN | Event.MOUSEUP | Event.FOCUS)
		window.onclick = null
		window.onfocus = null
	} else {
		enableForms()
	}
}

// Invoked by onFocus event handler of EVERY frame,
// return focus to dialog window if it's open.
function checkModal() {
	if (dialogWin.win && !dialogWin.win.closed) {
		dialogWin.win.focus()	
	}
}


//---------------------------------------------------------
//                      ticker functions
//---------------------------------------------------------


// width of the ticker
var tickerwidth=230

// height of the ticker
var tickerheight=67

// distance from the messagetext to the tickermarrgin (pixels)
var tickerpadding=5

// borderwidth of the ticker (pixels)
var borderwidth=0

// font-family
var fnt="Verdana,Arial Cyr,Helvetica Cyr,Arial,Ms Sans Serif"

// font-size of the text (px)
var fntsize=11

// font-color of the text
var fntcolor="000000"

// font-weight. Set a value between 1 to 9 to adjust the boldness
var fntweight=3

// backgroundcolor
var backgroundcolor="dadada"

// horizontal distance from the textlink to the popupbox (pixels)
//var xdistance=-tickerwidth-10
var xdistance=-10

// vertical distance from the textlink to the popupbox (pixels)
var ydistance=-84

// Do not edit the variables below
var topposition=200;
var rightposition=500;
var x=screen.width/2;
var y=screen.height/2;
var i_message=0;
var message;
var messagecontent="";
var messagebackground="";
fntweight=fntweight*100;



function getmessagebackground() {
	messagebackground="<table border=0 cellspacing=0 cellpadding=1><tr><td bgcolor=#1A5959><table border="+borderwidth+" width="+tickerwidth+" height="+tickerheight+" cellspacing=0 cellpadding=0><tr><td valign=top bgcolor='"+backgroundcolor+"'>";
	messagebackground+="&nbsp;</td></tr></table></td></tr></table>";
}

function getmessagecontent(defword,sometext) {
	messagecontent="<table border=0 cellspacing=0 cellpadding="+tickerpadding+" width="+tickerwidth+" height="+tickerheight+"><tr><td valign=top>";
	messagecontent+="<span style='position:relative; font-family:"+fnt+";color:"+fntcolor+";font-size:"+fntsize+"px;font-weight:"+fntweight+"'>" ;
	messagecontent+="<font color='"+fntcolor+"'>";
	messagecontent+="<b>"+defword+"</b><br>"+sometext;
	messagecontent+="</font>";
	messagecontent+="</span>";
	messagecontent+="</td></tr></table>";
}


function showmessage(word,linkmessage,myevent) {


	x = (document.layers) ? myevent.pageX : document.body.scrollLeft+event.clientX;
	y = (document.layers) ? myevent.pageY : document.body.scrollTop+event.clientY;

	leftposition = x;

	getmessagebackground();
	myword=word;
    getmessagecontent(myword,linkmessage);

	rightposition=x+xdistance+tickerwidth;
	topposition = y-ydistance-tickerheight;
	leftposition=x+xdistance;


	if (document.all) {


		document.all.ticker.style.posLeft=leftposition;
		document.all.ticker.style.posTop=topposition;
		document.all.tickerbg.style.posLeft=leftposition;
		document.all.tickerbg.style.posTop=topposition;
		tickerbg.innerHTML=messagebackground;
		document.all.ticker.style.visibility="visible";
		document.all.tickerbg.style.visibility="visible";
		ticker.innerHTML=messagecontent;

	}

	if (document.layers) {

		document.captureEvents(Event.MOUSEMOVE);

		document.ticker.left=leftposition
		document.ticker.top=topposition
		document.tickerbg.left=leftposition
		document.tickerbg.top=topposition
		document.tickerbg.document.write(messagebackground)
		document.tickerbg.document.close()
		document.ticker.visibility="visible"
		document.tickerbg.visibility="visible"

		document.ticker.document.write(messagecontent)
		document.ticker.document.close()

	}

}



function hideticker() {



	if (document.all) {
		document.all.ticker.style.visibility="hidden"
		document.all.tickerbg.style.visibility="hidden"
	}

	if (document.layers) {
		document.ticker.visibility="hidden"
		document.tickerbg.visibility="hidden"
	}
}


function replace(string,text,by) {
// Replaces text with by in string
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;
    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;
    var newstr = string.substring(0,i) + by;
    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,by);
    return newstr;
}

function jsCloseRefresh() {
	if (window.opener!=null)
	{

		if (variableFromEditRubriik_id!='undefined' && variableFromEditRubriik_id!=null && variableFromEditRubriik_id!='')
			{

				mylocation = ''+window.opener.location+'';
				mylocation = replace(mylocation,'?id=','?old_id=');
				mylocation = replace(mylocation,'&id=','&old_id=');
				temp= mylocation.indexOf('?');
				if (temp == -1) {
				mylocation+='?id='+variableFromEditRubriik_id;
				} else {
				mylocation+='&id='+variableFromEditRubriik_id;};
				window.opener.location=mylocation;

			} else {window.opener.location=window.opener.location;}
	}
	window.close();
}

function do_perm(first,seccond) {
  self.opener.location.replace(first+'&puu_keel='+seccond);
  self.close();
}

//---------------------------------------------------------
//                      Form Check
//---------------------------------------------------------

var whitespace = " \t\n\r";

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

function isWhitespace (s) {
	var i;

    if (isEmpty(s)) return true;

    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    return true;
}

function check_string (theField,alert_txt) {
	  if (isWhitespace(theField.value)) {
		if(!isWhitespace(alert_txt)) {
			alert(alert_txt);
		}
		//Trick to fool stupid browsers
		if(theField.focus()){};
		return false;
	  } else {
		return true;
	  }
	}

function check_email (theField,alert_txt){
	 var s = theField.value;
    // is s whitespace?
    if (isWhitespace(s)) {
		if(!isWhitespace(alert_txt)) {
			alert(alert_txt);
		}
		//Trick to fool stupid browsers
		if(theField.focus()){};
		return false;
	}
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) {
		if(!isWhitespace(alert_txt)) {
			alert(alert_txt);
		}
		//Trick to fool stupid browsers
		if(theField.focus()){};
		return false; 
	} else {
		i += 2;
	}

    // look for .
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }

    // there must be at least one character after the .
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) {
		if(!isWhitespace(alert_txt)) {
			alert(alert_txt);
		}
		//Trick to fool stupid browsers
		if(theField.focus()){};
		return false;
	} else {
		return true;
	}
}

//---------------------------------------------------------
//                Metadata Required Field
//---------------------------------------------------------

var metadata_required_fields = new Array();

function metadata_reguire_field() {
	alert('asas');
}

//---------------------------------------------------------
//              Shopping cart functionality
//---------------------------------------------------------

function add_to_cart(formname,page,prod) {
	var qty;

	qty = eval('document.forms["'+formname+'"].qty'+prod+'.value');

	if (isEmpty(qty)) {
		qty = 1;
	}
	if (isWhitespace(qty)) {
		qty = 1;
	}
	
	avapopup(page + '?add=' + prod + '&qty=' + qty, 'add2cart', 250, 150, 'no');
}

function del_from_cart(formname,page,prod) {
	window.location.replace(page + '&del=' + prod);
}

function to_cart() {
	if(window.name=='add2cart' && window.opener) {
		window.opener.location.replace('./index.php?op=cart');
		window.close();
	} else {
		window.location.replace('./index.php?op=cart');
	}
}

function save_cart(page) {
	avapopup(page + '?op=save', 'savecart', 250, 100, 'no');
}

function setCookie(name, value, expire,path) {
	document.cookie = name + "=" + escape(value)+((expire == null)?"":(";expires="+expire.toGMTString()))
}

function changeCookie(data,path) {
	var today = new Date();
	var expires = new Date();
	expires.setTime(today.getTime() + 3600*24*31);
	setCookie("saurus_shoppingcart", data, expires,path);
}

// Returns safe filename
// strips out special chars & spaces, replaces with "_"
// Usage: safename = safe_filename("Süsteemi fail");
function safe_filename(name) {
	var safename = name.toString();
	var re = new RegExp("(\\W+)", "g");
	safename = safename.replace(re, "_");
	return safename;
}