/* Molssoft JS scripts */
(function(){
//START
/* Shortages */
var d = document, w = window, undefined='undefined';

var mingx = window.mingx = {
	init : function(){
		this.detectClientInfo.init();
		this.browser = {
			os:		this.detectClientInfo.os,
			name:	this.detectClientInfo.browser,
			version:this.detectClientInfo.version
		};
		/*
		 @Special msie version
		*/
		this.isIE = (this.browser.name=='Explorer');
	},
	
	/**
		@Browser and OS Detection 
	*/
	detectClientInfo : {
		init: function () {
			this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
			this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
			this.os = this.searchString(this.dataOS) || "an unknown OS";
		},
		searchString: function (data) {
			for (var i=0;i<data.length;i++)	{
				var dataString = data[i].string;
				var dataProp = data[i].prop;
				this.versionSearchString = data[i].versionSearch || data[i].identity;
				if (dataString) {
					if (dataString.indexOf(data[i].subString) != -1)
						return data[i].identity;
				}
				else if (dataProp)
					return data[i].identity;
			}
		},
		searchVersion: function (dataString) {
			var index = dataString.indexOf(this.versionSearchString);
			if (index == -1) return;
			return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		},
		
		// patterns , info
		dataBrowser: [
			{
				string: navigator.userAgent,
				subString: "Chrome",
				identity: "Chrome"
			},
			{ 	string: navigator.userAgent,
				subString: "OmniWeb",
				versionSearch: "OmniWeb/",
				identity: "OmniWeb"
			},
			{
				string: navigator.vendor,
				subString: "Apple",
				identity: "Safari",
				versionSearch: "Version"
			},
			{
				prop: window.opera,
				identity: "Opera"
			},
			{
				string: navigator.vendor,
				subString: "iCab",
				identity: "iCab"
			},
			{
				string: navigator.vendor,
				subString: "KDE",
				identity: "Konqueror"
			},
			{
				string: navigator.userAgent,
				subString: "Firefox",
				identity: "Firefox"
			},
			{
				string: navigator.vendor,
				subString: "Camino",
				identity: "Camino"
			},
			{		// for newer Netscapes (6+)
				string: navigator.userAgent,
				subString: "Netscape",
				identity: "Netscape"
			},
			{
				string: navigator.userAgent,
				subString: "MSIE",
				identity: "Explorer",
				versionSearch: "MSIE"
			},
			{
				string: navigator.userAgent,
				subString: "Gecko",
				identity: "Mozilla",
				versionSearch: "rv"
			},
			{ 		// for older Netscapes (4-)
				string: navigator.userAgent,
				subString: "Mozilla",
				identity: "Netscape",
				versionSearch: "Mozilla"
			}
		],
		dataOS : [
			{
				string: navigator.platform,
				subString: "Win",
				identity: "Windows"
			},
			{
				string: navigator.platform,
				subString: "Mac",
				identity: "Mac"
			},
			{
				   string: navigator.userAgent,
				   subString: "iPhone",
				   identity: "iPhone/iPod"
			},
			{
				string: navigator.platform,
				subString: "Linux",
				identity: "Linux"
			},
			{
				string: navigator.platform,
				subString: "BSD",
				identity: "BSD"
			}
		]
	},
	
	/**	@Event attaching 
	 * 	@parameters: DOMElement, eventName( without "ON") , callbackFunction
	*/
	addEvent : function(elelement, type, fn){
		if (w.addEventListener){
			elelement.addEventListener(type, fn, false);
		} else if (w.attachEvent){
			var f = function(){
			  fn.call(elelement, w.event);
			};
			elelement.attachEvent('on' + type, f);
		}
	},
	
	/**
		@Returns element's absolute offset
		@In IE returns false values;
	*/
	getOffset : function(node){
		var top = 0, left = 0;
		do{
			top += node.offsetTop
			left += node.offsetLeft
		} while(node = node.offsetParent);
		return {left : left,top : top};
	},
	
	getSize : function(node){
		return {
			width:	node.offsetWidth,
			height:	node.offsetHeight
		}
	},
	
	getRelativeCoordinates : function(event, reference) {
		var x, y;
		event = event || window.event;
		var el = event.target || event.srcElement;

		if (!window.opera && typeof event.offsetX != undefined) {
		  // Use offset coordinates and find common offsetParent
		  var pos = { x: event.offsetX, y: event.offsetY };
		  // Send the coordinates upwards through the offsetParent chain.
		  var e = el;
		  while (e) {
			e.mouseX = pos.x;
			e.mouseY = pos.y;
			pos.x += e.offsetLeft;
			pos.y += e.offsetTop;
			e = e.offsetParent;
		  }
		  // Look for the coordinates starting from the reference element.
		  var e = reference;
		  var offset = { x: 0, y: 0 }
		  while (e) {
			if (typeof e.mouseX != undefined) {
			  x = e.mouseX - offset.x;
			  y = e.mouseY - offset.y;
			  break;
			}
			offset.x += e.offsetLeft;
			offset.y += e.offsetTop;
			e = e.offsetParent;
		  }
		  // Reset stored coordinates
		  e = el;
		  while (e) {
			e.mouseX = undefined;
			e.mouseY = undefined;
			e = e.offsetParent;
		  }
		}
		else {
		  // Use absolute coordinates
		  var pos = mingx.getOffset(reference);
		  x = event.pageX  - pos.left;
		  y = event.pageY - pos.top;
		}
		// Subtract distance to middle
		
		return { x: x, y: y };
	},
	
	/**
		@Crossbrowser mouse coordinates
	 */
	getMouseCoords : function(e){
		// pageX/Y is not supported in IE
		// http://www.quirksmode.org/dom/w3c_cssom.html	
		if (!e.pageX && e.clientX){
			return {
				x: e.clientX + d.body.scrollLeft + d.documentElement.scrollLeft,
				y: e.clientY + d.body.scrollTop + d.documentElement.scrollTop
			};
		}
		return {
			x: e.pageX,
			y: e.pageY
		};
	},
	
	getCoords : function(node){
		var offset = mingx.getOffset(node);
		var res = {
			left: offset.left,
			right: (offset.left + node.offsetWidth),
			top: offset.top,
			bottom: (offset.top + node.offsetHeight)
		};
		return res;
	},
	parseFunction : function(func){
		if(typeof(func)=='string'){
			func=eval("if(typeof(" + func + ")=='function'){" + func + ".valueOf();} else null;");
		} else if(typeof(func)!='function'){
			func = null;
		}
		return func;
	},
	/**
		@Return XMLDomElement from string
	*/
	parseXML : function(response){
		//IE Rocks!
		try{
			xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async="false";
			xmlDoc.loadXML(response);
		}catch(e){
			var parser=new DOMParser();
			var xmlDoc=parser.parseFromString(response,"text/xml");
		}
		
		return xmlDoc;
	},
	
	/**
		@Checkes whether s<string> exists in obj<object,array,hash>
	*/
	inArray : function(obj,s){
		if(typeof(obj)=='object'){
			for(var i in obj){
				if(obj[i]==s){
					return true;
				}
			}
		}
		return false;
	},
	
	/**
		@Posts request through form
	*/
	postRequest : function(a,b){
		var f = d.createElement('FORM');
		f.setAttribute('action',a);
		f.setAttribute('method','post');
		if(typeof(b)=='object'){
			for (var k in b){
				var i = d.createElement("input");
				i.setAttribute("type", "hidden");
				i.setAttribute("name", k);
				i.value = b[k];
				f.appendChild(i);
			}
		}
		d.body.appendChild(f);
		f.submit();
	}
}
mingx.init();

/* AJAX object */
var ajax = window.ajax = function(){
;
}

/** 
	@Returns xmlHTTPRequest object 
*/
ajax.getHTTPObject = function(){
	var xmlhttp;
	// Internet Explorer  
	if(window.ActiveXObject){  
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");    
		}
		catch(e){
			try{
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e){
				xmlhttp = false;
			}
		}
	}
	else if(window.XMLHttpRequest){     
		// Firefox, Opera 8.0+, Safari  
		try{
			xmlhttp = new XMLHttpRequest();  
		}
		catch(e){
			xmlhttp = false;
		}
	}
	return xmlhttp;
}
ajax.prototype.getHTTPObject = ajax.getHTTPObject;
ajax.xmlhttp = ajax.getHTTPObject();

/**	@Forms request, encodes parameters , so that &, and ' ", and other specific characters could be passed
	@Parameter can be one dimensional , or NNN dimensional array/object 
	@Example : ajax.formRequest({test: {test:1},test2:2});   result:  test[test]=1&test2=2  
*/
ajax.formRequest = function(params,path){
	var key,request = '';
	if(typeof(params)=='object'){
		var param;
		for (var param in params){
			if(typeof(path)==undefined || path==''){
				key=param;
				path='';
			}else {
				key="[" + param + "]";
			}
			if(typeof(params[param])=='object'){
				request+=ajax.formRequest(params[param],path+key);
			}else {
				request+= "&" + path + key + "=" + encodeURIComponent(params[param]);
			}
		}
	} else {
		return "";
	}
	return request.substring(1);
}
ajax.prototype.formRequest = ajax.formRequest;

/**
	@Send request
*/
ajax.exec = function(url, params, callback,sync,method,xmlhttp){
	if(!url){
		return false;
	}
	if(typeof(xmlhttp)!='object'){
		xmlhttp = ajax.xmlhttp;
	}
	if(xmlhttp.readyState!=4 && xmlhttp.readyState!=0){
		// Request already being sent
		return false;
	}
	// depending on method forms request parameters
	if(typeof(method)==undefined || method!="GET"){
		method="POST";
		var parameters=ajax.formRequest(params);
	} else {
		url = "?" + ajax.formRequest(params);
		var parameters = null;
	}
	if(typeof(sync)==undefined || sync!==false){
		sync=true;
	}
	
	// Forms call back function, if it was passed as a string
	callback = mingx.parseFunction(callback);
	xmlhttp.open(method,url,sync);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	
	xmlhttp.onreadystatechange = function() {
		if(xmlhttp.readyState==4){
			//alert(xmlhttp.responseText);
			if (callback) {
				callback.call(xmlhttp,xmlhttp.responseText);//izsaucam funkciju, kuras nosaukums padots parametrā
			}
		}
	};
	
	// nosūta pieprasījumu
	xmlhttp.send(parameters);
}
/** 
	@Submits all form data through ajax , now supports file uploading through iframe, automatically selects best method (AJAx||Iframe), though mannualy can be configured too
	@Parameters:
		formObj - HTMLFormElement
		url - if not supplied or null uses form action attribute
		callback - callback function
		exceptions - list of elements that need to be excluded from request, format as [ 'firstElementName', 'ElementWithThisNameWillBeExcluded'] ;
		sync - sync status, by default async
		method - if not supplied uses form method attribute, by default post;
*/
ajax.execForm = ajax.submitForm = function(formObj,url,callback,exceptions,sync,method,useiframe){
	if(typeof(formObj.tagName)==undefined || formObj.tagName!='FORM'){
		return false;
	}
	
	var params = [];
	var disabled = [];
	var UsingIframe = false;
	!useiframe || (UsingIframe=true);
	
	formCycle:
		for(var i in formObj.elements){
			var element = formObj.elements[i];
			var ex = mingx.inArray(exceptions,element.name);
			if(UsingIframe||element.name==undefined||!element.type||element.type.toLowerCase()=='image'||element.type.toLowerCase()=='button'||element.type.toLowerCase()=='reset'||ex){
				//Precaution
				if(UsingIframe&&ex){
					element.setAttribute('disabled',true);
					disabled.push(element);
				}
				continue;
			} else if(element.tagName=='SELECT'){
				var name = element.name;
				var value = element.options[element.selectedIndex].value;
			} else if(element.type.toLowerCase()=='file'){
				UsingIframe = true;
				continue formCycle;
				break;
			} else {
				var name = element.name;
				var value = element.value;
			}
			params[name] = value;
		}
	if(url==undefined || url==null){
		url = formObj.getAttribute("action");
	}
	if(method==undefined || method==null){
		method = formObj.getAttribute("method").toUpperCase();
	}
	if(UsingIframe){
		var frame = ajax.fileUpload._iframe();
		formObj.setAttribute("target",frame.getAttribute("name"));
		formObj.setAttribute("method","POST");
		formObj.setAttribute("action",url);
		formObj.setAttribute("enctype","multipart/form-data");
		ajax.fileUpload._addMethods.call({onComplete:callback},frame);
		formObj.submit();
		if(disabled.length>0){
			for(var i in disabled){
				disabled[i].disabled = false;
			}
		}
		return true;
	} else {
		return ajax.exec(url, params, callback,sync,method);
	}
}

/* FILE UPLOAD HANDLING */
/*
	Usage: ajax.fileUpload('file','http://www.lv',{param:'parameter'}); 
		@field - form input field name
		@url - page url
		@data - additional parameters
		@onChange - callback function, wich is called whenever file is selected , is called as a method of fileUpload object
			@example:	var onChange = function(file){
									if(file.indexOf('.mov')>0){
										return true;
									} else {
										return false; 
									}
								}
								if autoSubmit parameter is set to FALSE, then affects file submition
		@onSubmit - callback function is called before actual file submition, passed arguments:  fileName, possibleIframeID, possibleCancelFunction
				- results affecets file submition
		@onComplete - passed arguments: response , is called as a method of fileUpload object
		@autoSubmit - affects file submition, if set to true, onChange doesn't
		
		# all callback functions, data and autoSubmit are optional parameters;
		# required arguments - field, url
*/
ajax.fileUpload = function(elementID,field,url,data,onChange,onSubmit,onComplete,autoSubmit){
	var upload_button = d.getElementById(elementID);
	if(!upload_button){
		return false;
	}
	this.field = field;
	this.url = url;
	this.data = data;
	this.autoSubmit = (typeof(autoSubmit)=='undefined')?true:autoSubmit;
	this.field = field;
	this.upload_button = upload_button;
	this.file = ajax.fileUpload._fileInput(this.field);
	this.relativeCoordinates = false;
	this.mouseOverFile = false;
	ajax.fileUpload.mouseEvents.call(this);
	
	// Forms call back function, if it was passed as a string
	onSubmit = mingx.parseFunction(onSubmit);
	if(onSubmit==null){
		onSubmit = function(){return true;};
	}
	this.onSubmit = onSubmit;
	
	onChange = mingx.parseFunction(onChange);
	if(onChange==null){
		onChange = function(){};
	}
	this.onChange = onChange;
	
	onComplete = mingx.parseFunction(onComplete);
	this.onComplete = onComplete;
	
	var self = this;
	// if autoSubmit true, on change raises form submition.
	mingx.addEvent(this.file,'change',function(){
		if(self.file.value!='' && (self.onChange.call(self,self.file.value)==true || self.autoSubmit==true)){
			ajax.fileUpload._postFile.call(self);
		} else {
			self.file.value = '';
		}
	});
}

ajax.spice_listz= function(){//pievieno garšvielu sarakstam
	var xmlDoc=ajax.responseXML.documentElement;
	var spice_title = xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
	var container = document.getElementById('spice_list');
	var new_spice = document.createElement('li');
	new_spice.appendChild(document.createTextNode(spice_title))
	container.appendChild(new_spice, container.firstChild);
	return;
	//alert(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue);
}

/* Creates hidden iframe */
/* Returns iframe ID */
ajax.fileUpload._iframe_counter = 0;
ajax.fileUpload._iframe = function(){
	var ifrm_id = "ajaxFileUpload_"+ajax.fileUpload._iframe_counter;
	// IE HACK, because it ignores lines >>ifrm.setAttribute("name", ifrm_id);
	try {
		ifrm = document.createElement("<iframe name=\"" + ifrm_id + "\">");
	} catch (ex) {
		ifrm = document.createElement("IFRAME");
	}
	ifrm.setAttribute("src", "javascript:false;");
	ifrm.setAttribute("name", ifrm_id);
	ifrm.setAttribute("id", ifrm_id);
	ifrm.style.width = 0;
	ifrm.style.height = 0;
	ifrm.style.display = "none";
	d.body.appendChild(ifrm); 
	
	ajax.fileUpload._iframe_counter++;
	
	return ifrm;
}

ajax.fileUpload._form = function(iframe,action){
	if(iframe.tagName!='IFRAME'){
		return false;
	}
	
	var form_id = iframe.id + "_form";
	try{
		var form = d.createElement("<form method=\"post\" enctype=\"multipart/form-data\"></form>");
	} catch(ex){
		var form = d.createElement("FORM");
	}
	form.setAttribute("method", "POST");
	form.setAttribute("enctype", "multipart/form-data");
	form.setAttribute("name", form_id);
	form.setAttribute("id", form_id);
	form.setAttribute("target", iframe.getAttribute("name"));
	form.action = action;
	
	d.body.appendChild(form); 
	return form;
}

/* Creates file input object */
ajax.fileUpload._hiddenInputs = function(data,form){
	// Create hidden input element for each data key
	if(typeof(data)!='object'){
		return;
	}
	
	for (var key in data){
		var input = d.createElement("input");
		input.setAttribute("type", "hidden");
		input.setAttribute("name", key);
		input.value = data[key];
		form.appendChild(input);
	}
}

ajax.fileUpload._fileInput_counter = 0;
ajax.fileUpload._fileInput = function(fname){
	ajax.fileUpload._fileInput_counter++;
	
	var input = d.createElement("input");
	var file_id = "ajaxFileUpload_" + ajax.fileUpload._fileInput_counter + "_file";
	input.setAttribute("id", file_id);
	input.setAttribute("type", "file");
	input.setAttribute("name", fname);
	var styles = {
		'position' : 'absolute'
		,'margin': '-5px 0 0 -180px'
		,'padding': 0
		,'width': '220px'
		,'height': '30px'
		,'opacity': 0
		,'cursor': 'pointer'
		,'display' : 'none'
		,'left':0
		,'top':0
		,'zIndex' :  99999
	};
	for(var i in styles){
		input.style[i] = styles[i];
	}
	// IE Fix
	if (!(input.style.opacity==="0")){
		input.style.filter = "alpha(opacity=0)";
	}
	
	d.body.appendChild(input);
	
	return input;
}

ajax.fileUpload._postFile = function(){
	var possible_ifram_id = "ajaxFileUpload_"+ajax.fileUpload._iframe_counter;
	if(this.onSubmit.call(this,this.file.value,possible_ifram_id,function(){ajax.fileUpload.cancelUpload(possible_ifram_id);})==false){
		return;
	}
	var iframe = ajax.fileUpload._iframe();
	ajax.fileUpload._addMethods.call(this,iframe);
	var form = ajax.fileUpload._form(iframe,this.url);
	ajax.fileUpload._hiddenInputs(this.data,form);
	form.appendChild(this.file);
	form.submit();
	d.body.removeChild(form);
	form = null;
	this.file = null;
	
	/* Create new form */
	this.file = ajax.fileUpload._fileInput(this.field);
	var self = this;
	// if autoSubmit true, on change raises form submition.
	mingx.addEvent(this.file,'change',function(){
		if(self.file.value!='' && (self.onChange.call(self,self.file.value)==true || self.autoSubmit==true)){
			ajax.fileUpload._postFile.call(self);
		} else {
			self.file.value = '';
		}
	});
	
}

ajax.fileUpload.cancelUpload = function(iframeID){
	try{
		d.body.removeChild(d.getElementById(iframeID));
	}catch(ex){
		return;
	}
}

ajax.fileUpload.mouseEvents = function(){
	var self = this;
	mingx.addEvent(document, 'mousemove', function(e){
		if (!self.file || !self.mouseOverFile){
			return;
		}
		
		var c = mingx.getMouseCoords(e);
		self.relativeCoordinates = mingx.getRelativeCoordinates(e,self.upload_button);
		
		if (self.relativeCoordinates.x>0 && self.relativeCoordinates.y>0){
			self.file.style.top = c.y + 'px';
			self.file.style.left = c.x + 'px';
			self.file.style.display = 'block';
		} else {
			ajax.fileUpload.mouseOut.call(self);
		}
	});
	mingx.addEvent(self.upload_button, 'mouseover', function(e){
		if (!self.file || self.mouseOverFile){
			return;
		}
		self.mouseOverFile = true;
		self.relativeCoordinates = mingx.getRelativeCoordinates(e,self.upload_button);
	});
	mingx.addEvent(self.upload_button,'mouseout',function(e){ajax.fileUpload.mouseOut.call(self);});
	!mingx.isIE || mingx.addEvent(self.file,'click',function(e){var self = this;window.setTimeout(function(){self.style.display='none';},0);});
}

ajax.fileUpload.mouseOut = function(){
	this.mouseOverFile = false;
	this.file.style.display = 'block';
}

ajax.fileUpload._addMethods = function(iframe){
	var self = this;
	var passEvent = false;
	mingx.addEvent(iframe, 'load', function(){
		if (passEvent == false && iframe.src == "about:blank"){
			// Fix busy state in FF3
			setTimeout(function() {
				d.body.removeChild(iframe);
			}, 0);
			return;
		}
		// Opera hack
		if(window.opera && passEvent==false){
			passEvent = true;
			iframe.src = "about:blank";
			return;
		}
		// IE,FF fix
		var doc = iframe.contentDocument ? iframe.contentDocument : frames[iframe.id].document;
		var response = doc.body.innerHTML;
		if(typeof(self.onComplete)=='function'){
			self.onComplete.call(self,response);
		}
		passEvent = false;
		iframe.src = "about:blank"; //load event fired
	});
}

// END
})();