﻿////////////////////////////////////////////////////////////////////////
// Shared Function Library v1.3.4
// 2006-12-08 14:22:13
// SiC
////////////////////////////////////////////////////////////////////////

//----------------------------------------------------------
// Cookies Manager
//----------------------------------------------------------
function $cookies(method, name, value, ttl) {

	switch(method){
		case "get":
			var cookieArray = document.cookie.split("; ");
			for(var i=0; i<cookieArray.length; i++) {
				var item = cookieArray[i].split("=");
				if(item[0] == name){
					return item[1];
				}
			}
			return "";
			break;

		case "set":
			if(!ttl) ttl = 30;
			var date = new Date();
			date.setTime(date.getTime() + (ttl * 24*60*60*1000));
			document.cookie = name + '=' + value + '; expires=' + date.toGMTString() + '; path=/';
			break;

		case "del":
			document.cookie = name + '=;expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/';
			break;

	}

}


//----------------------------------------------------------
// Parse QueryString into Object
//----------------------------------------------------------
function $parseQueryString(urlString) {

	var result = {};

	var pos = urlString.indexOf("?");
	if(pos < 0) return result;

	var query = urlString.substr(pos + 1, urlString.length);
	query = query.split("&");

	for(var i=0; i<query.length;i++){
		pos = query[i].indexOf("=");
		var key = query[i].substr(0, pos);
		var value = query[i].substr(pos + 1, query[i].length);
		result[key] = value;
	}

	return result;

}


//----------------------------------------------------------
// Show/Hide Element
//----------------------------------------------------------
function $toggleElement(id, method, style){

	var obj = document.getElementById(id);
	if(!obj) return false;

	if(!style) style = "block";

	switch(method){
		case "show":
			obj.style.display = style;
			return true;
			break;

		case "hide":
			obj.style.display = "none";
			return false;
			break;

		default:
			if(obj.style.display != "none"){
				obj.style.display = "none";
				return false;
			}else{
				obj.style.display = style;
				return true;
			}

	}

}


//----------------------------------------------------------
// Shortcut for document.write and object.innerHTML
//----------------------------------------------------------
function $write(content, id, append){

	if(id){
		var obj = document.getElementById(id);
		if(obj){
			if(append){
				obj.innerHTML += content;
			}else{
				obj.innerHTML = content;
			}
			return;
		}
	}

	document.write(content);

}


//----------------------------------------------------------
// Read Language String
//----------------------------------------------------------
/*function $lang(label, section){

	this.defaultSection = "Options";

	if(!section) section = this.defaultSection;

	// Try load from language file
	var str = external.max_Lang(section, label);
	if(str != "") return str;

	// Try load default data
//	str = maxOptions.lang[label];
	if(!str) return "[" + label + "@" + section + "]";

	return str;

}

//----------------------------------------------------------
// Write Language String
//----------------------------------------------------------
function $writeLang(label, section){
	document.write($lang(label, section));
}
*/

//----------------------------------------------------------
// HTML Encode
//----------------------------------------------------------
function $encodeHTML(strText, isTextArea){

	if(strText == undefined) return "";
	if(typeof(strText) != "string" ) return "";

	strText = strText.replace(/\&/g, "&amp;");
	strText = strText.replace(/\>/g, "&gt;");
	strText = strText.replace(/\</g, "&lt;");
	strText = strText.replace(/\"/g, "&quot;");
	strText = strText.replace(/\'/g, "&#39;");

	if(!isTextArea) strText = strText.replace(/\n/g, "<br/>");

	return strText;

}


//----------------------------------------------------------
// Sanitize HTML - Remove Malicious HTML Codes
//----------------------------------------------------------
function $sanitizeHTML(strHTML, arrAllowedTags){

	if(strHTML == undefined) return "";
	if(typeof(strHTML) != "string" ) return "";

	if(arrAllowedTags == undefined){
		arrAllowedTags = {
			"br": {},
			"b": {},
			"strong": {},
			"u": {},
			"em": {},
			"ul": {},
			"ol": {},
			"li": {},
			"blockquote": {
				"style": {invalid: "expression|script"}
			},
			"p": {
				"align": {valid: "left|center|right"},
				"style": {invalid: "expression|script"}
			},
			"span": {
				"style": {invalid: "expression|script"}
			},
			"div": {
				"align": {valid: "left|center|right"},
				"style": {invalid: "expression|script"}
			},
			"a": {
				"href": {valid: "^(http|https|ftp|mailto)\:"},
				"title": {},
				"target": {}
			},
			"img": {
				"src": {valid: "^(http|ftp):"},
				"alt": {}
			}
		};
	}

	// Loop through all open tags
	var re = /\<([^\/].*?)(\/)?\>/ig;
	while( (arrMatch = re.exec(strHTML)) != null){

		// Process Tags
		var sourceLength = arrMatch[1].length;
		var arrParts = arrMatch[1].split(" ");
		var targetString = "";

		for(var item in arrAllowedTags){

			// Check for Allowed Tags
			var tagName = arrParts[0];
			if(arrAllowedTags[tagName]){

				// Allowed Tags
				for(var i=1; i<arrParts.length; i++){

					// Check for attributes
					var pos = arrParts[i].indexOf("=");
					if(pos<1){

							// Not Found - Remove it
							arrParts.splice(i, 1);
							i--;

					}else{

						// Found
						var attrName = arrParts[i].substr(0, pos);
						var attrValue = arrParts[i].substr(pos+1, arrParts[i].length);

						// Remove quotes and encode inside content
						if(attrValue.indexOf('"')==0 || attrValue.indexOf("'")==0){
							attrValue = attrValue.substr(1, attrValue.length);
							attrValue = attrValue.substr(0, attrValue.length-1);
						}

						//Check For allowed attributes
						if(arrAllowedTags[tagName][attrName]){

							// Found
							// Do Validation
							if(arrAllowedTags[tagName][attrName].valid){
								var attrRe = new RegExp(arrAllowedTags[tagName][attrName].valid, "ig");
								if(!attrRe.test(attrValue)){
									// Not Found - Remove it
									arrParts.splice(i, 1);
									i--;
									continue;
								}
							}

							//Check for invalid content
							if(arrAllowedTags[tagName][attrName].invalid){
								var attrRe = new RegExp(arrAllowedTags[tagName][attrName].invalid, "ig");
								if(attrRe.test(attrValue)){
									// Not Found - Remove it
									arrParts.splice(i, 1);
									i--;
									continue;
								}
							}

							// Re-assemble the attribute item
							attrValue = attrValue.replace(/\"/ig, "&quot;");
							arrParts[i] = attrName + '="' + attrValue + '"';

						}else{
							arrParts.splice(i, 1);
							i--;
						}

					}

				}

				targetString = "<" + arrParts.join(" ") + arrMatch[2] + ">";

			}else{

				// Forbidden Tags - Remove it
				targetString = "";

			}

		}

		// Update String
		strHTML = strHTML.replace(arrMatch[0], targetString);

		// Set RegExp Position
		re.lastIndex += targetString.length - sourceLength;

	}

	return strHTML;

}


//----------------------------------------------------------
// Sanitize URL - Remove Malicious Codes
//----------------------------------------------------------
function $sanitizeURL(strURL){

	if(strURL == undefined) return "";
	if(typeof(strURL) != "string" ) return "";

	var re = /^(.*?)script:/ig;
	if(re.test(strURL)) return "";

	re = /^about:/ig;
	if(re.test(strURL)) return "";

	strURL = strURL.replace(/</ig, "%3C");
	strURL = strURL.replace(/>/ig, "%3E");
	strURL = strURL.replace(/ /ig, "%20");

	return strURL;

}


//----------------------------------------------------------
// Clone an object/array
//----------------------------------------------------------
function $cloneObject(obj){

	if(typeof obj != "object") return obj;

	var newObj;

	if(obj instanceof Array){
		// Clone Array
		newObj = [];
		for(var i=0; i<obj.length; i++){
			if(typeof obj[i] == "object"){
				newObj[i] = $cloneObject(obj[i]);
			}else{
				newObj[i] = obj[i];
			}
		}
	}else{
		// Clone Object
		newObj = {};
		for(i in obj){
			if(typeof obj[i] == "object"){
				newObj[i] = $cloneObject(obj[i]);
			}else{
				newObj[i] = obj[i];
			}
		}
	}

	return newObj;

}


//----------------------------------------------------------
// Convert Object to JSON String
//----------------------------------------------------------
function $encodeJSON(obj){

	switch(typeof(obj)){
		case "object":
			if(obj instanceof Array){
				var out = [];
				for(var i=0; i<obj.length; i++){
					var t = $encodeJSON(obj[i]);
					if(t){
						out.push(t);
					}
				}
				out = "[\n" + out.join(",\n") + "\n]";
			}else if(obj instanceof Object){
				var out = [];
				for(label in obj){
					var l = $encodeJSON(label);
					var t = $encodeJSON(obj[label]);
					if(t){
						out.push(l + ":" + t);
					}
				}
				out = "{\n" + out.join(",\n") + "\n}";
			}
			return out;
			break;
		case "string":
			var str = obj;
			str = str.replace(/\\"/g, '\\\\"');
			str = str.replace(/\r/g, '\\r');
			str = str.replace(/\t/g, '\\t');
			str = str.replace(/\n/g, '\\n');
			str = str.replace(/\f/g, '\\f');
			str = str.replace(/\"/g, '\\"');
			return '"' + str + '"';
			break;
		case "number":
			return isFinite(obj) ? String(obj) : 'null';
			break;
		case "boolean":
			return String(obj);
			break;
		case "null":
			return "null";
			break;
	}

}


//----------------------------------------------------------
// Trim a string
//----------------------------------------------------------
function $trim(str){

	str = str.replace(/^[\s\n\t]*/g, "");
	str = str.replace(/[\s\n\t]*$/g, "");

	return str;

}


//----------------------------------------------------------
// Cut a string
//----------------------------------------------------------
function $cutString(str, length){

	if(str == undefined) return "";

	var strLen, tLen, charCode;
	strLen = str.length;
	tLen = 0;

	for(var i=0; i<strLen; i++){
		charCode = str.charCodeAt(i);
		if(charCode<0||charCode>255){ tLen+=2 }else{ tLen++ }
		if(tLen>=length){ return str.substr(0,i)+"..."; }
	}

	return str;

}


//----------------------------------------------------------
// Debug functions
//----------------------------------------------------------
function $dump(obj){

	alert($encodeJSON(obj));

}