var irave = new Object();
irave.callInitFunction = new Array();
irave.callInitFunctionData = new Array();
irave.hashAjax = new Object();
irave.autoCheckTime = new Object();
irave.autoCheckTime.timerID = '';
/** init irave onload **/
irave.init = function() {
//	var TIME_CHECK_NEW_MSG = TIME_CHECK_NEW_MSG;
	popup.init();
	irave.checkNew(false);
	setInterval('irave.checkNew(false)', TIME_CHECK_NEW_MSG*1000);
	if(ifirave.setInboxWidth!= undefined ) {
		ifirave.setInboxWidth();
		window.onresize = ifirave.setInboxWidth;
	}
	for(var i=0; i<irave.callInitFunction.length; i++) {
		irave.callInitFunction[i](irave.callInitFunctionData);
	}

}
//for fade out
irave.setAutoCheckTime = function(funcCheck){
	irave.autoCheckTime.timerID = setInterval(funcCheck, 30*1000);
}
irave.clearAutoCheckTime = function(){
	window.clearInterval(irave.autoCheckTime.timerID);
}
//end
/* Add function to call after irave init all data */
irave.addInitCallback = function(callfunction, data) {
	irave.callInitFunction.push(callfunction);
	irave.callInitFunctionData.push(data);
}

irave.initAjaxBack = function(callFunction) {
	irave.hashAjax.callFunction = callFunction;
	irave.hashAjax.currentHash = "";
	irave.hashAjax.timerHashID = setInterval( "irave.checkAjaxBack()", 50 );
}

irave.addAjaxBack = function(newHash) {
	if(newHash){
		window.location.hash = newHash;
	}
}

//
// Using
// addOnloadEvent(myFunctionName);
// addOnloadEvent(function(){ myFunctionName('myArgument') });
//
irave.addOnloadEvent = function(fnc){
  if ( typeof window.addEventListener != "undefined" )
    window.addEventListener( "load", fnc, false );
  else if ( typeof window.attachEvent != "undefined" ) {
    window.attachEvent( "onload", fnc );
  }
  else {
    if ( window.onload != null ) {
      var oldOnload = window.onload;
      window.onload = function ( e ) {
        oldOnload( e );
        window[fnc]();
      };
    }
    else
      window.onload = fnc;
  }
}

irave.checkAjaxBack = function() {
	if ( window.location.hash != irave.hashAjax.currentHash ) {
		irave.hashAjax.currentHash = window.location.hash;
		irave.hashAjax.callFunction( irave.hashAjax.currentHash.substr( 1,  irave.hashAjax.currentHash.length) );
	}
}

irave.stopAjaxBack = function() {
	window.clearInterval(irave.hashAjax.timerHashID);
}

/** Check New Message */
irave.checkNew = function (forced) {
	//alert("Just Check New " + forced);
	if (!forced) {
		irave.lastCheckTime = CKM.getCookie('lastCheckNew');
		if (irave.lastCheckTime == null) {
			irave.lastCheckTime = 0;
		}
		irave.lastCheckTime = new Date(irave.lastCheckTime);

		//get current time
		var currentTime = new Date();
		//alert((currentTime - irave.lastCheckTime).toString());
		if (currentTime - irave.lastCheckTime <= TIME_CHECK_NEW_MSG * 1000) {
			return;
		}
	}
	//alert('Calling ajaxCheckNew');
	var url = "index.php?act=ajaxCheckNew";
	var request = createAjaxRequest(true);
	request.open('POST', url, true);
	request.onreadystatechange = function(){
		if (request.readyState == 4 && request.status == 200) {
			CKM.setCookie('lastCheckNew', currentTime ? currentTime.toString(): (new Date()).toString());
			var objChecked = request.responseText.strip().evalJSON();
			//alert($("msg").className+"outside");
			if (!objChecked[0].unreadMsg)
				objChecked[0].unreadMsg = 0;
			if (!objChecked[1].unreadMsg)
				objChecked[1].unreadMsg = 0;
			if (!objChecked[2].unreadMsg)
				objChecked[2].unreadMsg = 0;
			if (!objChecked[3].unreadMsg)
				objChecked[3].unreadMsg = 0;
			if (!objChecked[4].unreadMsg)
				objChecked[4].unreadMsg = 0;
			if (!objChecked[5].unreadMsg)
				objChecked[5].unreadMsg = 0;
			if (objChecked[0].hasNewMessage == true || objChecked[8].hasNewMessage == true) {
				//alert($("msg").className+"Before");
				if ($("msg").className == "inbox")
					$("msg").className = "inboxNew";
				if ($("msg").className == "inboxActive")
					$("msg").className = "inboxActiveNew";
			/*if ($("msg").className== "inboxActiveNew" || $("msg").className== "inboxActive"){
			 ifirave.folder.setMessageNumber(objChecked[0].unreadMsg,objChecked[3].unreadMsg,objChecked[4].unreadMsg,objChecked[1].unreadMsg,objChecked[5].unreadMsg);
			 }*/
			}
			if ($("msg").className == "inboxActiveNew" || $("msg").className == "inboxActive") {
				ifirave.folder.setMessageNumber(objChecked[0].unreadMsg, objChecked[3].unreadMsg, objChecked[4].unreadMsg, objChecked[1].unreadMsg, objChecked[5].unreadMsg, objChecked[8].unreadMsg);
				if (objChecked[6].isListMessage == 0) {
					if (ifirave.folder.retrieveMessage != undefined)
						ifirave.folder.retrieveMessage();
				}
				if (objChecked[1].hasNewMessage == true && objChecked[7].isListMessage == 0 && jsVars.global.currentFolder == 'Junk') {
					if (ifirave.folder.retrieveMessage != undefined)
						ifirave.folder.retrieveMessage();
				}
			}
			if ($('pendingCommentSubMenu')) {
				if ($('pendingCommentSubMenu').className != 'current' && objChecked.pendingCommentEvent.newEvent == true) {
					$('pendingCommentSubMenu').className = 'newPending';
					$('pendingCommentSubMenu').show();
					if (objChecked.pendingCommentEvent.count) {
						$('pendingCommentSubMenuCount').innerHTML = '(' + objChecked.pendingCommentEvent.count + ')';
					}
				}
			}
			if ($('pendingPhotoSubMenu')) {
				if ($('pendingPhotoSubMenu').className != 'current' && objChecked.pendingPhotoEvent.newEvent == true) {
					$('pendingPhotoSubMenu').className = 'newPending';
					$('pendingPhotoSubMenu').show();
					if (objChecked.pendingPhotoEvent.count) {
						$('pendingPhotoSubMenuCount').innerHTML = '(' + objChecked.pendingPhotoEvent.count + ')';
					}
				}
			}

		}
	}
	request.send(null);

}

irave.hideCommentNotification = function () {
    var notification = $$(".commentNotification")
    if(notification && notification.length>0) {
        for(var i=0; i<notification.length; i++) {
            notification[i].hide();
        }
    }
}

irave.setValueForElement = function(ele, str) {
	if(ele)	ele.value = str;
}

// Handle go to at Main Navigation
irave.processToGo = function(pageName, url) {
	if(jsVars.global.pageName.indexOf("Compose") != -1) {
		if(ifirave.compose.isComposedMessage()) {
			var str = '<div align="center" style="padding:30px 10px 30px;"><div>' + jsVals.jconfirm.discardMessage	+ '</div>'
						+ '<div class="buttonPopup" style="width:90%">'
							+ '<a class="tabRight" onclick="popup.clickNo(); popup.hide()"><em class="tabLeft"><span class="tabInner" id="butNo">Back to Message</span></em></a>'
							+ '<a class="tabRight" onclick="javascript:popup.clickYes(); popup.hide()"><em class="tabLeft"><span class="tabInner" id="butYes">Continue</span></em></a>'
						+ '</div>'
					+ '</div>';

			popup.popItUp(null, {
				confirmStr: str,
				realConfirmStr: jsVals.jconfirm.discardMessage,
				html: true,
				clickYes: function () {
					navigate = true;
					irave.goTo(pageName);
				},
				clickNo: function () {
				}
			},350,115);
		}
		else {
			navigate = true;
			irave.goTo(pageName);
		}
	}
	else
		irave.goTo(pageName);
}

/** Go to page */
irave.goTo = function(page) {
	//irave.dataReset();
	//alert(page);
	page = (page=='Messages') ? "Inbox" : page;
	window.location = 'index.php?act=if' + page;
	jsVars.global.pageName = page;
}

irave.updateSelectedItem = function() {
}

/** Change nav to match with page name */
irave.hightLightMenu = function (name) {
	if( typeof(NO_HIGHLIGHT) == "undefined"){
		if (name == "Gallery") {
			$("gal").className = "galleryActive";
			$("msg").className = "inbox";
			$("ctact").className = "contact";
			$("sett").className = "setting";
		} else if (name == "Message") {
			$("msg").className = "inboxActive";
			$("gal").className = "gallery";
			$("ctact").className = "contact";
			$("sett").className = "setting";
		} else if (name == "Settings") {
			$("sett").className = "settingActive";
			$("gal").className = "gallery";
			$("msg").className = "inbox";
			$("ctact").className = "contact";
		} else if (name == "Contacts") {
			$("ctact").className = "contactActive";
			$("gal").className = "gallery";
			$("msg").className = "inbox";
			$("sett").className = "setting";
		}
	}
}

//use for footer
irave.showTOS = function (showing) {
    if ($('uploaderContainer'))
		$('uploaderContainer').hide();
    var url = IRAVE_URL_ROOT + "index.php?act=tos&isPublic=false";
	if (showing) {
    	popup.hide();
    	setTimeout(function() {popup.popItUp(url, null, 720, 490);},1000);
    } else {
    	popup.popItUp(url, null, 720, 490);
    }
}

//use for footer
irave.pbshowTOS = function (showing) {
    if ($('uploaderContainer'))
		$('uploaderContainer').hide();
    var url = "index.php?act=tos&isPublic=true";
	if (showing) {
    	popup.hide();
    	setTimeout(function() {popup.popItUp(url, null, 720, 490);},1000);
    } else {
    	popup.popItUp(url, null, 720, 490);
    }
}


//use for footer
irave.showPrivacy = function (showing) {
    /*if ($('uploaderContainer'))
		$('uploaderContainer').hide();*/
    var url = IRAVE_URL_ROOT + "index.php?act=privacy&isPublic=false";
    if (showing) {
    	popup.hide();
    	setTimeout(function() {popup.popItUp(url, null, 720, 490);},1000);
    } else {

    	popup.popItUp(url, null, 720, 490);
    }
}

//use for footer
irave.pbshowPrivacy = function (showing) {
    /*if ($('uploaderContainer'))
		$('uploaderContainer').hide();*/
    var url =  "index.php?act=privacy&isPublic=true";
    if (showing) {
    	popup.hide();
    	setTimeout(function() {popup.popItUp(url, null, 720, 490);},1000);
    } else {
    	popup.popItUp(url, null, 720, 490);
    }
}


irave.selectButton = function(name) {
	if (name == "Gallery") {
		//$('buttonGallery').className = "btn_blue";
	} else if (name == "GalleryPhoto") {
		//$('buttonGallery').className = "btn_grey";
	} else if (name == "GalleryClip") {
		//$('buttonGallery').className = "btn_grey";
	} else if (name == "GalleryLink") {
		//$('buttonGallery').className = "btn_grey";
	} else if (name == "GalleryMisc") {
		//$('buttonGallery').className = "btn_grey";
	}
}

/** Update number of unread messages */
irave.updateNumberOfUnread = function () {
	return true // comment out to move to new version
	var url = IRAVE_URL_ROOT + "index.php?act=ajaxCheckNew";
	new Ajax.Request (url, {
		method: "post",
		parameters: {count:1},
		onSuccess: function(transport) {
			var objChecked = transport.responseText.strip().evalJSON();

			$("urNInbox").innerHTML = objChecked[0].unreadMsg?objChecked[0].unreadMsg:0;
			$("urNJunk").innerHTML = objChecked[1].unreadMsg?objChecked[1].unreadMsg:0;
		}
	});
}

/** Reset global Data on change page */
irave.dataReset = function () {
	jsVars.global.sender = null;
	jsVars.global.sortField = "date";
	jsVars.global.sortOrder = "DESC";
	jsVars.global.pageNum = 1;
	jsVars.global.currentFolder = "Inbox";
}

irave.checkRetrieveMsgBySender = function(email) {
	var page = jsVars.global.pageName;
	if(page != 'Messages' && page != 'Inbox' && page != 'Sent' && page != 'Draft' && page != 'Junk' && page != 'Trash')
		return;
	//window.frames['page'].ifirave.folder.retrieveMessageBySender(email);
	ifirave.folder.retrieveMessageBySender(email);
}

irave.inviteFriends = function() {
	if ($('uploaderContainer'))
		$('uploaderContainer').hide();
    var url = IRAVE_URL_ROOT + "index.php?act=inviteFriendsPopup";
	popup.popItUp(url,null,438,163, 'headerEmails');

}

/**
 * Show popup Quick View Profile
 * Nguyen Lu 28-08-2008
 */
irave.viewProfile = function(email) {
	popup.setDimension(440,200);
	parent.popup.popItUp("index.php?act=ajaxContactQuickView&email=" + email,null,440,200,'userInfor');
}
//use for invite friends
irave.updateContactListForAuto = function() {
	var url = IRAVE_URL_ROOT + "index.php?act=ajaxAutocomplete";
	new Ajax.Request(url,
		{
			method: 'post',
			onSuccess: function(transport) {
				$('notIraveContactListForAuto').innerHTML = transport.responseText;
			}
		});
}


irave.initInviteAtHeader = function() {
	if($("headerEmails") && $("autoInvitedEmailList")){
	        new AutoCompleteTextbox($("headerEmails"), $("autoInvitedEmailList"), $("notIraveContactListForAuto"), false, true);
	}
}

irave.submitSearchKeyWord = function() {
	var keyWord = $('messKeyword').value.trim();
	if(keyWord.length == 0 ) {
		popup.popItUp(null, jsVals.jalert.msgSearchEmpty, 380, 115);
	}
	else {
		//window.location='index.php?act=ifInbox&keyWord=' + keyWord ;
		window.location='index.php?act=if' + jsVars.global.currentFolder + '&keyWord=' + keyWord ;
	}
}
