/*********************************************
		
			MISC FUNCTIONS
		
**********************************************/

var e = window.encodeURIComponent ? encodeURIComponent : escape;
var uE = window.decodeURIComponent ? decodeURIComponent : unescape;

function addLoadEvent(func)
{
  var oldonload = window.onload;
  if (typeof window.onload != "function") {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

//Get all the elements of the given classname of the given tag.
function getElementsByClassName(classname,tag) {
	if(!tag) tag = "*";
	var anchs =  document.getElementsByTagName(tag);
	var total_anchs = anchs.length;
	var regexp = new RegExp("\\b" + classname + "\\b");
	var class_items = new Array()

	for(var i=0;i<total_anchs;i++) { //Go thru all the links seaching for the class name
		var this_item = anchs[i];
		if(regexp.test(this_item.className)) {
			class_items.push(this_item);
		}
	}
	return class_items;
}

function inc_x (pID) {
	return korv_muuda(pID, 1);
}

function dec_x (pID) {
	return korv_muuda(pID, -1);
}

function korv_muuda (pID, palju_muuta) {
	item_id = "cart_item[" + pID + "]";
	v22rtus = 0;
	if (document.cart[item_id].value) {
		v22rtus = parseInt(document.cart[item_id].value);
		if (!v22rtus) { v22rtus = 0; }
	}
	v22rtus += palju_muuta;
	if (v22rtus < 0) { v22rtus = 0; }
	if (v22rtus > 9999) { v22rtus = 9999; }
	document.cart[item_id].value = v22rtus;
	document.cart[item_id].focus();
	return false;
}

function dbl_click (inp) {
	if (navigator.appName == "Microsoft Internet Explorer") { inp.onclick(); }
}

function getElement(id) {
	if (document.getElementById) {
		return document.getElementById(id);
	}
	else if (document.all) {
		return document.all[id];
	}
	else if (document.layers) {
		return document.layers[id];
	}
}

/*********************************************
		
			AJAX FUNCTIONS
		
**********************************************/

var strResDataErr = new String("Tekkis tõrge!\nTundmatu vastus serverilt, palun proovige mõne hetke pärast uuesti.\nID: [:ID:] ([:INFO:])");

function isValidXMLObject (res) { // V 2.0
	try {
		if (typeof res.getElementsByTagName("isError")[0] != "undefined") {
			return true;
		}
	} catch (e) {
		//
	}
	return false;
}

function isValidEmail (str) {
	return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

function functionName (res) { // V 2.2
	var longstring = new String(res);
	var brokenstring = longstring.split(" ");
	return brokenstring[1];
}

function isValidResource (res) { // V 2.1
	return (typeof res == "undefined" || res == null) ? false : true;
}

// convert all characters to lowercase to simplify testing
var agt = navigator.userAgent.toLowerCase();
var appVer = navigator.appVersion.toLowerCase();

// *** BROWSER VERSION ***

var is_minor = parseFloat(appVer);
var is_major = parseInt(is_minor);
var is_opera = (agt.indexOf("opera") != -1);
var iePos  = appVer.indexOf('msie');
var is_ie   = ((iePos!=-1) && (!is_opera));
var is_ie7up = (is_ie && (agt.indexOf("msie 7.") != -1));

// threadsafe asynchronous XMLHTTPRequest code V 2.4
var TAVersion = "2.4";

function requestData (url, data, callback, dType, cApply) {
    resXML = (dType == "XML" ? true : false);
    // we use a javascript feature here called "inner functions"
    // using these means the local variables retain their values after the outer function
    // has returned. this is useful for thread safety, so
    // reassigning the onreadystatechange function doesn\'t stomp over earlier requests.
    function ajaxBindCallback() {
        if (ajaxRequest.readyState == 4) {
            if (ajaxRequest.status == 200) {
                if (ajaxCallback) {
                    if (resXML) {
                        eval(ajaxCallback + "(ajaxRequest.responseXML.documentElement, ajaxApply)");
                    } else {
                        eval(ajaxCallback + "(ajaxRequest.responseText, ajaxApply)");
                    }
                } else {
                    alert("No callback defined!");
                }
            } else {
                alert("There was a problem retrieving the XML data!\n\nStatus: " + ajaxRequest.statusText + " (" + ajaxRequest.status + ")\n\nResponse:\n" + ajaxRequest.responseText);
            }
        }
    }
    
    // use a local variable to hold our request and callback until the inner function is called...
    var ajaxRequest = false;
    var ajaxCallback = callback;
    var ajaxApply = cApply;
    
    // bind our callback then hit the server...
    ajaxRequest = getHTTPObject(resXML);
    
    if (!ajaxRequest) {
        return false;
    } else {
        ajaxRequest.onreadystatechange = ajaxBindCallback;
        try {
            ajaxRequest.open("POST", url, true);
        } catch (e) {
        	alert(e);
            return false;
        }
        ajaxRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        ajaxRequest.setRequestHeader("X-Prototype-Version", TAVersion);
        ajaxRequest.setRequestHeader("Connection", "close");
        ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        ajaxRequest.send(data);
        return true;
    }
    return false;
}

function getHTTPObject (resXML) {
	var xO = false;
	if (typeof XMLHttpRequest != "undefined") {
		try {
			xO = new XMLHttpRequest();
			if (resXML) {
				xO.overrideMimeType("text/xml");
			} else {
				xO.overrideMimeType("text/html");
			}
			return xO;
		} catch (e) {
			if (is_ie7up) {
				xO = new XMLHttpRequest();
				return xO;
			} else {
				xO = false;
			}
		}
	} else {
		var msxmls = new Array(
			"Msxml2.XMLHTTP",
			"Msxml2.XMLHTTP.5.0",
			"Msxml2.XMLHTTP.4.0",
			"Msxml2.XMLHTTP.3.0",
			"Microsoft.XMLHTTP"
		);
		for (var i = 0; i < msxmls.length; i++) {
			var msxml = msxmls[i]; 
			try {
				xO = new ActiveXObject(msxml);
				return xO;
			} catch(e) {
				xO = false;
			}
		}
		
	}
	return xO;
}

function __X (x) {
	var Request = "url" in x ? x.url : selfUrl;
	var Destination = "dest" in x ? x.dest : "";
	var callback = "func" in x ? x.func : "";
	var postData = "post" in x ? x.post : "";
	var Params = "parm" in x ? x.parm : "r.responseText";
	var oLoaded = "loaded" in x ? x.loaded : "";
	
	new Ajax.Request(Request,
	{
		method:"post",
		postBody:postData,
		contentType:"application/x-www-form-urlencoded",
		onCreate: function() {
		},
		onLoaded: function() {
			if (!oLoaded.empty()) {
				eval(oLoaded);
			}
		},
		onSuccess: function(r) {
//			if (r.responseText) {
				if (!Destination.empty()) {
					$(Destination).update(r.responseText);
				} else if (!callback.empty()) {
					eval(callback + "(" + Params + ")");
				}
//			} else {
//				alert("No response from server...");
//			}
			delete r;
		},
		onFailure: function() {
			alert("Something went wrong...");
		}
	});
}
