var timeToOpenNotify = 1000;
var timeToCloseNotify = 2000;

var ifirave = new Object();

/* utils */
var util = new Object();

/* Get param by javascript */
util.getParamURL = function(strParamName) {
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ) {
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ) {
      if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ) {
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return strReturn;
}

/* Check the browser is internet explorer or not */
util.isIE = function() {
	if (navigator.appVersion.indexOf("MSIE") != -1)
		return true;
}

util.isCurrentOwner = function (uid) {
    if(uid != parent.jsVars.global.uid) {
        parent.document.location.reload();
    }
}

util.getClassNameFromType = function (type) {
	if(type == "image")
		return "thmb_pic_m";
	else if(type == "video")
		return "thmb_clip_m";
	else if(type == "link")
		return "thmb_link_m";
	else { //application
		return "thmb_misc_m";
	}
}

util.getBrowserSize = function () {
	if( typeof(window.innerWidth) == 'number') {
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if(document.body && (document.body.clientWidth || document.body.clientHeight )) {
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return {"width": myWidth, "height": myHeight};
}

util.alignCenter = function (obj) {
	if(obj.style.display == "none") return;
	var browserSize = this.getBrowserSize();

	// Get current top and left
	var ie5=document.all && !window.opera;
	var ns6=document.getElementById;
	var iecompattest = (document.compatMode && document.compatMode.indexOf("CSS")!=-1)? document.documentElement : document.body;
	var dsocleft = ie5? iecompattest.scrollLeft : pageXOffset;
	var dsoctop = ie5? iecompattest.scrollTop : pageYOffset;

	obj.style.left = ((browserSize.width/2 - parseInt(obj.style.width)/2) + dsocleft) + "px";
	obj.style.top = ((browserSize.height/2 - parseInt(obj.style.height)/2) + dsoctop) + "px";
}

//ajax loading
util.initLoading = function() {
	var loading = {
		onCreate: function() {
			if($('loading') && Ajax.activeRequestCount > 0) {
				//popup.grayOut(true);
				$('loading').style.display = "block";
				$('loading').style.top = "115px";
				$('loading').style.right = "100px";
				//util.alignCenter($('loading'));
				//$('loading').setStyle({'opacity':1,'-moz-opacity':1,'filter':'alpha(opacity=100)'});
			}
		},
		onComplete: function() {
			if($('loading') && Ajax.activeRequestCount == 0) {
				//setTimeout("popup.grayOut(false);",1);
				//new Rico.Effect.FadeTo($('loading'), 0.0, 180, 1);
				setTimeout("$('loading').style.display = 'none';", 100);
			}
		}
	}
	Ajax.Responders.register(loading);
}

util.iframeGoto = function (src) {
	$('page').src = src;
	CKM.setCookie('currentPage', src);
}

/* Remove innner content of an element */
util.removeContent = function (id) {
	document.getElementById(id).innerHTML = "";
}

/* Check a value is numberic or not */
util.isNumberic = function (number) {

}

/* Check email is valid*/
util.isValidEmail = function (email) {

}

util.ineffectiveKeydown = function (ele) {
	ele.onkeydown = function() {
		return false;
	}
}

/* Include find by javascript */
util.include = function (url) {
	var XMLHttp = false;
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		XMLHttp = new XMLHttpRequest();
	else if (window.ActiveXObject){ // if IE
		try {
			XMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e){
			try{
				XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){}
		}
	}
	else
		return false;
	XMLHttp.open('GET', url, false); //get page synchronously
	XMLHttp.send(null);
	util.writeContent(XMLHttp);
}

util.writeContent = function (XMLHttp){
	if (window.location.href.indexOf("http")==-1 || XMLHttp.status==200)
		document.write(XMLHttp.responseText)
}

util.autoFitIframe = function (id){
	//$("contentWrapper").style.height = parseInt($("contentWrapper").offsetHeight) + 57 + "px";
}

util.autoFitMyGalleryDiv = function (){
	$("myGallery").style.height = parseInt($("newComposeID").offsetHeight) + 40 + "px";
}

util.inviteEmailsToIrave = function () {
	var emails = $("headerEmails").value.strip();
	if(emails == "" || emails == 'Invite your friends') {
		$("noticeBoard").innerHTML = jsVals.jalert.headerEmailsRequired;
		$("headerEmails").focus();
		return;
	}
	else {
		var result = validation.checkInvitedEmails(emails);

		if(!result) {
			return;
		}

		var invitedContacts = new Array();
		var str = {emails:result};
		invitedContacts.push(str);

		var url = "index.php?act=senInvitationAtHeader";
		setTimeout(function(){
			$('dialogueC').innerHTML = "";
			new Ajax.Request(url,{
				method: 'post',
				parameters: {emailsData: Object.toJSON(invitedContacts)},
				onSuccess: function(transport) {
					$('dialogueC').innerHTML = transport.responseText;
					popup.setDimension(440,120);

				}
			});
		}, 1000);

	}
}

/*notify*/
util.alert = function(obj, str, time) {
	var delta = Number(time/2);
	obj.innerHTML = str;
	obj.style.whiteSpace='nowrap';
	obj.style.margin='0px 0px';
	obj.style.padding='8px 8px';

	if(this.isIE())
		obj.style.position = "absolute";
	else
		obj.style.position = "fixed";

	obj.style.right = '0px';
	obj.style.top = '0px';

	new Rico.Effect.FadeTo(obj, 1, delta, 50);
}

util.closeAlert = function(obj, time) {
	var delta = Number(time/2);
	//closeNotify(obj, delta);
	setTimeout(function(){closeNotify(obj,delta);}, delta/2);
}


util.buildHref = function(action, params){
	if (serverVars.url.IRAVE_URL_GATEWAY) {
		var str = serverVars.url.IRAVE_URL_GATEWAY;
		str += '?act=' + action;

		if (params) {


			$H(params).each(function(pair) {
      			var property = pair.first(), attribute = pair.last();
	  			str += '&' + property + '=' + escape(attribute);
		//	for (var x in params) {
		//		str += '&' + x + '=' + params[x];
			});

		}
		return str;
	}
	return '';
}

loadingImage = function(theImage) {

	if (theImage == null) {
	}
	else {
		var idDivOutbound = 'div_' + theImage.id;
		var divOutbound = $(idDivOutbound);
		var divHideObject = divOutbound.previous(0);

		divHideObject.style.display = 'none';
		divOutbound.style.display = '';
	}
}

closeNotify = function (obj,delta) {
	new Rico.Effect.FadeTo(obj, 0, delta, 50);
}

/*drag drop senderbar*/
function DragNDropBar(container, option) {
	if(container == null) return;
	this.direction = "Y";
	this.container = container;
	var table = this.container.down(0);
	this.option = option;
	this.tablePos = this.getPosition(table);
	this.container.status = false;
	this.container.DragNDropBar = this;

	if(this.option != this.direction)
		this.maxRange = table.offsetWidth - this.container.offsetWidth;
	else
		this.maxRange = table.offsetHeight - this.container.offsetHeight;
	this.container.onmousedown = function(ev) {
		if(this.DragNDropBar.maxRange <= 0) this.status = false;
		else this.DragNDropBar.mouseDown(table, ev);
	}
	this.container.onmouseup = function () {
		this.status = false;
	}
	this.container.onmousemove = function (ev) {
		if(this.status == true) {
			var ev = ev || window.event;
			if(this.DragNDropBar.option != this.DragNDropBar.direction)
				table.style.left = this.DragNDropBar.mouseMove(parseInt(table.style.left), Event.pointerX(ev), this.DragNDropBar.prePointX, this.mouseOffset.x, this.DragNDropBar.tablePos.x, ev) + "px";
			else
				table.style.top = this.DragNDropBar.mouseMove(parseInt(table.style.top), Event.pointerY(ev), this.DragNDropBar.prePointY, this.mouseOffset.y, this.DragNDropBar.tablePos.y, ev) + "px";
		}
	}
}

DragNDropBar.prototype.mouseDown = function(table, evt) {
	var ev = evt || window.event;
	this.container.status = true;
	if(!table.style.left) table.style.left = "0px";
	if(!table.style.top) table.style.top = "0px";
	var otable = table;
	this.container.mouseOffset = this.getMouseOffset(otable, ev);
	this.prePointX = Event.pointerX(ev);
	this.prePointY = Event.pointerY(ev);
}

DragNDropBar.prototype.mouseMove = function(oldTableP, nextPoint, prePoint, mouseOffset, tablePos) {
	var moveRange = nextPoint - prePoint;
	if(moveRange > 0 && moveRange >= Math.abs(oldTableP))
		return 0;
	else if(moveRange < 0 && Math.abs(moveRange) >= this.maxRange - Math.abs(oldTableP))
		return -this.maxRange;
	else
		return nextPoint - mouseOffset - tablePos;
}

DragNDropBar.prototype.getMouseOffset = function(table, ev) {
	ev = ev || window.event;
	var docPos    = this.getPosition(table);
	var mousePosX  = Event.pointerX(ev);
	var mousePosY = Event.pointerY(ev);
	return {x:mousePosX - docPos.x, y:mousePosY - docPos.y};
}

DragNDropBar.prototype.getPosition = function(table) {
	var left = 0;
	var top  = 0;

	while (table.offsetParent){
		left += table.offsetLeft;
		top  += table.offsetTop;
		table     = table.offsetParent;
	}

	left += table.offsetLeft;
	top  += table.offsetTop;

	return {x:left, y:top};
}

function AutoCompleteTextbox_hide(textbox, container) {
	container.style.width = "0px";
	container.innerHTML = "";
	var iframe = document.getElementById(textbox.id+"_iframe");
	if (iframe) {
		iframe.style.visibility = 'hidden';
	}
	container.style.display = 'none';
}

/*Autocomplete*/
function AutoCompleteTextbox(textbox, container, contactList, overLaped, isPopUpOrTooMinSize) {
	//alert('test');
	this.overLaped = overLaped;
	this.isPopUpOrTooMinSize = isPopUpOrTooMinSize;
	this.tableID = "popupTable" + textbox.id;
	this.topBoundaryIndex = 0;
	this.visibleItemCount = 7;
	this.relativeCurrentIndex = 0;

	this.validItems = new Array();
	this.container = container;
	this.containerWidth = this.container.offsetWidth;
	this.textbox = textbox;
	this.timeoutId;
	this.characters;
	this.tbvalue = '';
	this.contactList = contactList;
	this.textbox.AutoCompleteTextbox = this;

	if(this.overLaped) {
		this.isIE = document.all ? true : false;
		//this.isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
		//this.isIE = '';

		// Prevent select dropdowns showing thru
		if (this.isIE) {
			this.iframe = document.createElement('iframe');
			this.iframe.id = textbox.id +'_iframe';
			this.iframe.style.position = 'absolute';
			this.iframe.style.top = '0';
			this.iframe.style.left = '0';
			this.iframe.style.width = '0px';
			this.iframe.style.height = '0px';
			this.iframe.style.zIndex = '98';
			this.iframe.style.visibility = 'hidden';

			this.textbox.parentNode.insertBefore(this.iframe, this.textbox);
		}
	}

	this.textbox.onkeyup = function(evt) {
		var crossEvent = (evt)? evt : event;
		if (crossEvent==null) crossEvent = (evt)? evt : parent.event;
		var keyCode = crossEvent.keyCode;
		var othis = this.AutoCompleteTextbox;
		clearTimeout(othis.timeoutId);
		if(keyCode == 38 || keyCode == 40 || keyCode == 13 || keyCode == 9 || keyCode == 27) return;
		else if ((keyCode != 16 && keyCode != 8 && keyCode < 32) || (keyCode >= 33 && keyCode < 46) || (keyCode >= 112 && keyCode <= 123)) return;
		else {
			othis.timeoutId = setTimeout(function(){othis.doOrdinaryKeyAction(crossEvent)}, 800);
		}
	}

	this.textbox.onkeydown = function(evt) {
		var crossEvent = (evt)? evt : event;
		if (crossEvent==null) crossEvent = (evt)? evt : parent.event;
		var keyCode = crossEvent.keyCode;
		var othis = this.AutoCompleteTextbox;
		if(keyCode == 38) this.AutoCompleteTextbox.doKeyUpAction(crossEvent);
		else if(keyCode == 40) this.AutoCompleteTextbox.doKeyDownAction(crossEvent);
		/*else if(keyCode == 9) {
			clearTimeout(othis.timeoutId);
			othis.doOrdinaryKeyAction(crossEvent);
			setTimeout(function(){othis.doEnterKeyAction(crossEvent)}, 800);
		}*/
		else if(keyCode == 13 || keyCode == Event.KEY_TAB) {
                        var tbvalue = this.value;
			if(validation.isEmpty(tbvalue) || !this.AutoCompleteTextbox.tableIsVisible()) {
				clearTimeout(othis.timeoutId);
				if($("headerInviteButton"))
					util.inviteEmailsToIrave();
			}
			else {
				this.AutoCompleteTextbox.doEnterKeyAction(crossEvent);
				return false;
			}
		}
		else if(keyCode == 27 || keyCode == 9) {
			clearTimeout(othis.timeoutId);
			this.AutoCompleteTextbox.disposeTable();
		}
	}
}

AutoCompleteTextbox.prototype.showTable = function(visibleItems) {
	this.disposeTable();
	if(this.isPopUpOrTooMinSize)
		var table = parent.document.createElement("TABLE");
	else
		var table = document.createElement("TABLE");
	table.id = this.tableID;
	table.className = "auto";
	if(! this.isPopUpOrTooMinSize) {
		table.style.top = Number(parseInt(this.textboxTop()) + parseInt(this.textbox.offsetHeight))+ "px";
		table.style.left = parseInt(this.textboxLeft()) + "px";
		table.style.width = parseInt(this.textbox.offsetWidth) + "px";
	}/*else{
		//YEN
		var cursor = {x:24, y:195};//{x:24, y:155};
    	//var e = window.event.keys();
    	//var keyCode = e.keyCode;
    	//var de = document.documentElement;
    	//var b = document.body;
    	//cursor.x = e.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
    	//cursor.y = e.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    	table.style.top = parseInt(cursor.y)+"px";
		table.style.left = parseInt(cursor.x)+"px";
	}*/

	for(var i = 0; i < visibleItems.length; i++) {
		var row = table.insertRow(-1);
		row.className = (i == this.relativeCurrentIndex)? "autoselected" : "autonormal";
		var cell = row.insertCell(-1);
		cell.id = i;
		cell.className = "autocell";
		cell.innerHTML = visibleItems[i];
		cell.AutoCompleteTextbox = this;
		cell.zIndex = '99';
		cell.onmousemove = function() {
			this.AutoCompleteTextbox.relativeCurrentIndex = parseInt(this.id);
			this.AutoCompleteTextbox.apply();
		}
		cell.onmousedown = function() {
			this.AutoCompleteTextbox.relativeCurrentIndex = parseInt(this.id);
			this.AutoCompleteTextbox.doEnterKeyAction();
		}
	}
	this.container.appendChild(table);
	this.container.style.width = this.containerWidth + "px";
	this.container.style.display = "block";

	if (this.isIE) {
            this.iframe.style.top    = table.style.top;
            this.iframe.style.left   = table.style.left;
            this.iframe.style.width  = table.offsetWidth;
            this.iframe.style.height = table.offsetHeight;

            this.iframe.style.visibility = 'visible';
	}
}

AutoCompleteTextbox.prototype.doKeyUpAction = function() {
	if(!this.tableIsVisible()) return;
	if(this.relativeCurrentIndex == 0 && this.topBoundaryIndex > 0) this.topBoundaryIndex--;
	else if(this.relativeCurrentIndex > 0) this.relativeCurrentIndex--;
	this.apply();
}

AutoCompleteTextbox.prototype.doKeyDownAction = function() {
	if(!this.tableIsVisible()) return;
	var limitCount = Math.min(this.validItems.length, this.visibleItemCount);
	if(this.relativeCurrentIndex == limitCount - 1) {
		if(this.topBoundaryIndex + this.visibleItemCount < this.validItems.length) this.topBoundaryIndex++;
	}
	else if(this.relativeCurrentIndex < limitCount) this.relativeCurrentIndex++;
	this.apply();
}

AutoCompleteTextbox.prototype.doEnterKeyAction = function() {
	if(this.tableIsVisible()) {
		var selectedValue = this.validItems[Number(this.topBoundaryIndex + this.relativeCurrentIndex)];
		var striped = selectedValue.replace("&lt;", "<");
		striped = striped.replace("&gt;", ">");
		var contact = validation.splitNameAndEmail(striped);
		var lastComma = this.textbox.value.lastIndexOf(',');
		if( lastComma != -1)
			tmpOldValue = this.textbox.value.substring(0, lastComma+2 );
		else
			tmpOldValue = "" ;

		if(validation.isValidExtraName_(contact.name))
			this.textbox.value = this.tbvalue + striped + ', ';
		else
			this.textbox.value = tmpOldValue + '"' + contact.name + '" <' + contact.email.strip() + '>, ';
	}
	this.disposeTable();
}

AutoCompleteTextbox.prototype.doOrdinaryKeyAction = function() {
	if(this.textbox.value.length == 0) {
		this.disposeTable();
		return;
	}
	var allTbValue = this.textbox.value;
	var semicolonArr = allTbValue.split(';');
	var lastEofSemiArr = semicolonArr[semicolonArr.length - 1].strip();
	if(lastEofSemiArr == "") {
		this.disposeTable();
		return;
	}
	var arr = lastEofSemiArr.split(',');
	var lastElement = arr[arr.length - 1].strip();
	if(lastElement != "") {
		this.characters = lastElement;
		if(semicolonArr.length == 1 && arr.length == 1) this.tbvalue = '';
		else
			this.tbvalue = allTbValue.substring(0, allTbValue.length - this.characters.length).strip() + " ";

		this.rebuild();
		this.validItems = this.getContactForAutocomplete();
		if(this.validItems.length > 0)
			this.apply();
	}
	else if(lastElement == "" || this.validItems.length == 0)
		this.disposeTable();
}

AutoCompleteTextbox.prototype.getContactForAutocomplete = function() {
	var contactListValue = this.contactList.innerHTML.evalJSON();
	var result = new Array();
	for(var i=0; i< contactListValue.length; i++) {
		var name = contactListValue[i]["name"];
		var email = contactListValue[i]["email"];
		if(this.characters == email || this.characters == name + "<" + email + ">")
			return new Array();
		var myExp = new RegExp("\^" + this.characters, "i");
		if(myExp.test(name) || myExp.test(email))
			result.push(name + "&lt;" + email + "&gt;");
	}
	return result;
}

AutoCompleteTextbox.prototype.rebuild = function() {
	this.disposeTable();
	this.validItems = new Array();
	this.relativeCurrentIndex = 0;
	this.topBoundaryIndex = 0;
}

AutoCompleteTextbox.prototype.apply = function() {
	var limitIndex = Math.min(this.validItems.length, this.visibleItemCount + this.topBoundaryIndex);
	var visibleItems = new Array();
	for(var index = this.topBoundaryIndex; index < limitIndex; index++)
		visibleItems.push(this.validItems[index]);
	this.showTable(visibleItems);
}

AutoCompleteTextbox.prototype.tableIsVisible = function() {
	return this.container.style.display != 'none';
}

AutoCompleteTextbox.prototype.disposeTable = function() {
	if(this.tableIsVisible()){
		this.hideContainer();
	}
}

AutoCompleteTextbox.prototype.textboxTop = function() {
    var top = 0;
    var currentElement = this.textbox;
    while(currentElement) {
        top += parseInt(currentElement.offsetTop);
        currentElement = currentElement.offsetParent;
    }
    return top;
}

AutoCompleteTextbox.prototype.textboxLeft = function() {
    var left = 0;
    var currentElement = this.textbox;
    while(currentElement) {
        left += parseInt(currentElement.offsetLeft);
        currentElement = currentElement.offsetParent;
    }
    return left;
}

AutoCompleteTextbox.prototype.hideContainer = function() {
	this.container.style.width = "0px";
	this.container.innerHTML = "";
	this.container.style.display = 'none';

	if(this.overLaped && this.iframe) {
    	       this.iframe.style.visibility = 'hidden';
	}
}

<!-- Cross Browser Utils -->
function createAjaxRequest(onError) {
	var xmlhttp = false;
    if (window.ActiveXObject) {
        // IE case
        try {
            if (navigator.userAgent.toLowerCase().indexOf('msie5') != -1) {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } else {
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
        } catch (e) {
            xmlhttp = false;
        }
    } else try {
        // Gecko case
        xmlhttp = new XMLHttpRequest();
    } catch (e) {
        xmlhttp = false;
    }

    if (!xmlhttp) {
        if (onError) {
            onError("Unable to create XMLHttpRequest in this browser.");
        }
    }
    return xmlhttp;
}

function getXY(e)
{
	var isIE = document.all?true:false;
    var cursor = {x:0, y:0};
    if (!isIE) {
        cursor.x = e.pageX;
    	cursor.y = e.pageY;
    }
    if (isIE) {
	    cursor.x = window.event.clientX + document.body.scrollLeft;
	    cursor.y = window.event.clientY + document.body.scrollTop;
    }
    return cursor;
}



/*
function calculateHtmlPosition(htmlstr, pos)
{
    if (pos <= -1)
        return -1;

    var htmlPos = 0;
    var isInsideTag = false;
    var cnt = 0;
    for (var i = 0; i < htmlstr.length; i++)
    {
        if (cnt>=pos)
            break;
        var currentChar = htmlstr.charAt(i);
		if (currentChar == "<")
		    isInsideTag = true;
        if (!isInsideTag)
            cnt++;
        if (currentChar ==">")
            isInsideTag = false;
    }
    return i;
}
*/

/* String function*/
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };


/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }

/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test()
{
  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
function core_md5(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Calculate the HMAC-MD5, of a key and some data
 */
function core_hmac_md5(key, data)
{
  var bkey = str2binl(key);
  if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
  return core_md5(opad.concat(hash), 512 + 128);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert a string to an array of little-endian words
 * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
 */
function str2binl(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}

/*
 * Convert an array of little-endian words to a string
 */
function binl2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
  return str;
}

/*
 * Convert an array of little-endian words to a hex string.
 */
function binl2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}

/*
 * Convert an array of little-endian words to a base-64 string
 */
function binl2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}

function pageAsChangeItem(oldItemPerPage, itemPerPage, currentPage){
	var page;
	var indexPhoto;
	if(currentPage == undefined || currentPage == 0){
		currentPage = 1;
	}
	indexPhoto = oldItemPerPage * (currentPage -1) + 1;
	page = parseInt(indexPhoto / itemPerPage + (indexPhoto%itemPerPage > 0 ? 1 : 0));
	return page;
}

function loadJsCssFile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

function addslashes( str ) {
    // Escapes single quote, double quotes and backslash characters in a string with backslashes
    //
    // version: 810.114
    // discuss at: http://phpjs.org/functions/addslashes
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // +   improved by: Nate
    // +   improved by: Onno Marsman
    // *     example 1: addslashes("kevin's birthday");
    // *     returns 1: 'kevin\'s birthday'

    return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");
}

//for fade out an photo
function removeClassName(divEl){
	if(divEl.indexOf('_') > -1){
		var arrEl = divEl.split('_');
		if(selectingIndex == arrEl[1]){ //define in tpl
			$(divEl).className = 'active';
		}else{
			$(divEl).className = '';
		}
	}else{
		$(divEl).className = '';
	}
}
function fadeOut(divEl){
	//
	setTimeout("removeClassName('"+divEl+"')",15000); // php time_nanosleep(5,1) === tre .... process
}
//end

/* Copy To Clipboard*/
var copy_time_out = null;
function copyToClipBoard(inElement) {
  if (inElement.createTextRange) {
    var range = inElement.createTextRange();
    if (range)
      range.execCommand('Copy');
  }
 else {
    var flashcopier = 'flashcopier';
    if(!document.getElementById(flashcopier)) {
      var divholder = document.createElement('div');
      divholder.id = flashcopier;
      document.body.appendChild(divholder);
    }
    document.getElementById(flashcopier).innerHTML = '';
    var divinfo = '<embed src="public/styles/default/images/clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopier).innerHTML = divinfo;
  }
}

function copyToClipBoard_(ele) {
	Copied = ele.createTextRange();
	Copied.execCommand("Copy");
}




