/*****************************************************
 * @author matias
 * General functions
 *****************************************************/
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

function openExternalUrl(url) {
	window.open(url);
}

function gotoURL(pageName, section, extraParams) {
	var url = pageName;
	activeSection[PARAM_INDEX_SECTION] = section;
	if (url.indexOf('?') >= 0) {
		url += '&';
	} else {
		if (extraParams) {
			url += '?';
		}
	}

	//if (oEnviroment.getLanguage().getID()) {
		//url += 'lang=' + oEnviroment.getLanguage().getID();
	//}

	if (extraParams) {
		url += '' + extraParams;
	}

	if (!oEnviroment.getDebugMode()) {
		window.location.href = url;
	} else {
		if (confirm('Redirect to other page? you will lose your debug console')) {
			window.location.href = url;
		}
	}
}

function openMemberDetail(section, member_id, tab) {
	if (!tab) tab = '';
	activeSection[PARAM_INDEX_SECTION] = section;
	window.location.href = 'index.php?lang=' + oEnviroment.getLanguage().getID() + '&member=' + member_id + '&tab=' + tab;
}

function openPendingRequests() {
	activeSection[PARAM_INDEX_SECTION] = 'mysquare';
	window.location.href = 'mySquare.php?lang=' + oEnviroment.getLanguage().getID() + '&tab=members&opt=requests';
}


function openPrivateMemberDetail(section, member_id) {
	if (!oEnviroment.getDebugMode()) {
		activeSection[PARAM_INDEX_SECTION] = section;
		window.location.href = 'privateProfile.php?lang=' + oEnviroment.getLanguage().getID() + '&member=' + member_id;
	} else {
		if (confirm('Redirect to other page? you will lose your debug console')) {
			activeSection[PARAM_INDEX_SECTION] = section;
			window.location.href = 'privateProfile.php?lang=' + oEnviroment.getLanguage().getID() + '&member=' + member_id;
		}
	}
}

function openVideoDetail(section, entry_id) {
	activeSection[PARAM_INDEX_SECTION] = section;
	window.location.href = 'myVideo.php?lang=' + oEnviroment.getLanguage().getID() + '&entry=' + entry_id;
}

function openSlideshowDetail(section, entry_id) {
	activeSection[PARAM_INDEX_SECTION] = section;
	window.location.href = 'mySlideshow.php?lang=' + oEnviroment.getLanguage().getID() + '&entry=' + entry_id;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) { returnString += c; }
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
		if (i==2) {this[i] = 29;}
   }
   return this;
}

function parseDay(dtStr) {
	var dtCh= "-";
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strDay=dtStr.substring(pos2+1);

	if (strDay.charAt(0)=="0" && strDay.length>1) { strDay=strDay.substring(1); }
	day=parseInt(strDay,10);

	return day;
}

function parseMonth(dtStr) {
	var dtCh= "-";
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strMonth=dtStr.substring(pos1+1,pos2);

	if (strMonth.charAt(0)=="0" && strMonth.length>1) { strMonth=strMonth.substring(1); }
	month=parseInt(strMonth, 10);

	return month;
}


function parseYear(dtStr) {
	var dtCh= "-";
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strYear=dtStr.substring(0, pos1);
	strYr=strYear;

	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) { strYr=strYr.substring(1); }
	}
	year=parseInt(strYr,10);
	return year;
}

/*****************************************************
 * Refresh detection functions
 *****************************************************/
// By default, turn refresh detection on
var refresh_prepare = 1;

function checkRefresh() {
	// Get the time now and convert to UTC seconds
	var today = new Date();
	var now = today.getUTCSeconds();
	var ret = false;

	// Get the cookie
	var cookie = document.cookie;
	var cookieArray = cookie.split('; ');

	// Parse the cookies: get the stored time
	for(var loop=0; loop < cookieArray.length; loop++)	{
		var nameValue = cookieArray[loop].split('=');

		// Get the cookie time stamp
		if( nameValue[0].toString() == 'SHTS' )	{
			var cookieTime = parseInt(nameValue[1], 10);
		}
		// Get the cookie page
		else if( nameValue[0].toString() == 'SHTSP' ) {
			var cookieName = nameValue[1];
		} else if (nameValue[0].toString() == 'MENU') {
				activeSection[PARAM_INDEX_SECTION] = nameValue[1];
		}

	}
	if (trim(activeSection[PARAM_INDEX_SECTION]).length == 0) {
		activeSection[PARAM_INDEX_SECTION] = 'main';
	}

	if( cookieName &&
		cookieTime &&
		cookieName == 'SQUA.RE') {
		// Refresh detected
		// Insert code here representing what to do on
		// a refresh

		// If you would like to toggle so this refresh code
		// is executed on every OTHER refresh, then
		// uncomment the following line
		// refresh_prepare = 0;
		ret = true;
	}

	// You may want to add code in an else here special
	// for fresh page loads
	return ret;
}

function prepareForRefresh() {
	if( refresh_prepare > 0 ) {

		// Turn refresh detection on so that if this
		// page gets quickly loaded, we know it's a refresh
		var today = new Date();
		var now = today.getUTCSeconds();
		document.cookie = 'SHTS=' + now + ';';
		document.cookie = 'SHTSP=SQUA.RE;';
		document.cookie = 'MENU=' + activeSection[PARAM_INDEX_SECTION] + ';';
		document.cookie = 'LANG=' + oEnviroment.getLanguage().getID() + ';';
	} else {
		// Refresh detection has been disabled
		document.cookie = 'SHTS=;';
		document.cookie = 'MENU=main;';
		document.cookie = 'LANG=1;';
	}
}

function saveLanguageCookie(language_id) {
	document.cookie = 'LANG=' + language_id + ';';
}

function getLanguageCookie() {
	// Get the cookie
	var cookie = document.cookie;
	var cookieArray = cookie.split('; ');
	var langugage_id=1;
	// Parse the cookies: get the stored time
	for(var loop=0; loop < cookieArray.length; loop++)	{
		var nameValue = cookieArray[loop].split('=');
		// Get the cookie time stamp
		if( nameValue[0].toString() == 'LANG' )	{
			language_id = parseInt(nameValue[1], 10);
		}

	}
	return langugage_id;
}

function disableRefreshDetection() {
	refresh_prepare = 0;
	return true;
}

function enableRefreshDetection() {
	refresh_prepare = 1;
	return true;
}


function buildPagination(container, start, pageSize, total) {
	var html = '';

	var prevPage = start - pageSize;
	var nextPage = start + pageSize;

	if (prevPage < 0) {prevPage = 0;}
	if (nextPage > total) {nextPage = total;}


	if (total > pageSize) {
		html += '<a href="javascript:goto_PrevPage()">&lt; Previous</a>&nbsp;|';
		var pageCounter = 0;
		while (pageCounter * pageSize < total) {
			var className = 'link';
			if (pageCounter == 0) { className = 'linkSelected'; }
			html += '&nbsp;<a class="' + className + '" id="page_' + pageCounter + '" href="javascript:goto_Page(' + (pageCounter * pageSize) + ')">' + (pageCounter + 1) +'</a>';
			pageCounter++;
		}

		html += '&nbsp;|&nbsp;<a href="javascript:goto_NextPage()">Next &gt;</a>';
	}

	html += '';
	$(container).innerHTML = html;
}

function changeElementVisibility(element_id, bVisible, hatcher) {
	var status = '';
	if (!bVisible) status = 'none';
	$(element_id).style.display =status;
	try {
		if (bVisible) {
			hatcher.src= "rsrc/button_sm_more-1.gif";
		} else {
			hatcher.src= "rsrc/button_sm_more-0.gif";
		}

	} catch (e) {

	}
}

function showHideElement(element_id) {
	var status = ($(element_id).style.display == 'none');
	changeElementVisibility(element_id, status);
}

function logServiceMSG(serviceName, msg) {
	var html = "---------------------------------------------------------------------------------------Service MSG Start " + serviceName + "---------------------------------------------------------------------------------------<br/>";
	html += "Message: " + msg + "<br>";
	html += "---------------------------------------------------------------------------------------Service MSG End " + serviceName + "---------------------------------------------------------------------------------------<br/>";
	$('debugConsole').innerHTML = $('debugConsole').innerHTML + '<br/>' + html;
}

function logServiceCall(service) {
	var html = "---------------------------------------------------------------------------------------Service Call Start " + service.getName() + "---------------------------------------------------------------------------------------<br/>";
	html += "Name: " + service.getName() + "<br>";
	html += "SID: " + service.getSID() + "<br>";
	html += "Method: " + service.getMethod() + "<br>";

	var parameters = "";
    for (i=0; i < service.getParamCount(); i++) {
		if (i>0) { parameters += '&'; }
		parameters += service.getKey(i) + "=" + service.getParameterByIndex(i);
	}
	html += "Parameters: " + parameters + "<br>";
	html += "---------------------------------------------------------------------------------------Service Call End " + service.getName() + "---------------------------------------------------------------------------------------<br/>";

	$('debugConsole').innerHTML = $('debugConsole').innerHTML + '<br/>' + html;
}

function logServiceResponse(service) {
	var html = "---------------------------------------------------------------------------------------Service Response Start " + service.getName() + "---------------------------------------------------------------------------------------<br/>";
	html += "Error: " + service.getResult().getErrorCode() + "<br>";
	html += "Description: " + service.getResult().getDescription() + "<br>";
	html += "Start: " + service.getResult().getStart() + "<br>";
	html += "PageCount: " + service.getResult().rowCount() + "<br>";
	html += "Total: " + service.getResult().getTotal() + "<br>";

	html += "Response: <br>";
	while (service.getResult().hasNext()) {
		html += service.getResult().getCurrentRow() + "<br>";
		service.getResult().moveNext();
	}
	service.getResult().moveFirst();
	html += "---------------------------------------------------------------------------------------Service Response End " + service.getName() + "---------------------------------------------------------------------------------------<br/>";

	$('debugConsole').innerHTML = $('debugConsole').innerHTML + '<br/>' + html;
}

function logString(value) {
	$('debugConsole').innerHTML = $('debugConsole').innerHTML + '<br/>' + value;
}

/****************************************************************
 *  Mouse Wheel required functions Start
 ***************************************************************/

/** Event handler for mouse wheel event. */
function wheel(event){
        var delta = 0;
        if (!event) /* For IE. */
                event = window.event;
        if (event.wheelDelta) { /* IE/Opera. */
                delta = event.wheelDelta/120;
                /** In Opera 9, delta differs in sign as compared to IE.
                 */
                if (window.opera)
                        delta = -delta;
        } else if (event.detail) { /** Mozilla case. */
                /** In Mozilla, sign of delta is different than in IE.
                 * Also, delta is multiple of 3.
                 */
                delta = -event.detail/3;
        }

        /** If delta is nonzero, handle it.
         * Basically, delta is now positive if wheel was scrolled up,
         * and negative, if wheel was scrolled down.
         */
        if (delta)
                handle(delta);

		 /** Prevent default actions caused by mouse wheel.
         * That might be ugly, but we handle scrolls somehow
         * anyway, so don't bother here..
         */
        if (event.preventDefault)
                event.preventDefault();


	event.returnValue = false;
}

/** This is high-level function.
 * It must react to delta being more/less than zero.
 */
function handle(delta) {
	var scrollObj = null;
	if (oStrategy.getCurrentPage() == 'index.php') {
		if (oVLOG.isVisible()) {
			scrollObj = $("side_ctntBody");
		} else {
			if (hasWelcome) {
				scrollObj = $("txt_fullwelcome");
			} else {
				scrollObj = $("member_details_data");
			}
		}
	} else if (oStrategy.getCurrentPage() == 'mySquare.php') {
		scrollObj = $("side_ctntBody");
	}

    if (delta < 0) {
		scrollObj.scrollTop -= delta * 8
	} else {
		scrollObj.scrollTop -= delta * 8
	}
}

function initMouseWheel() {
	if (window.addEventListener)
        /** DOMMouseScroll is for mozilla. */
        window.addEventListener('DOMMouseScroll', wheel, false);
	/** IE/Opera. */
	window.onmousewheel = document.onmousewheel = wheel;
}
/****************************************************************
 *  Mouse Wheel required functions end
 ***************************************************************/

 function detectSafari() {
 	var agt=navigator.userAgent.toLowerCase();
 	if (agt.indexOf('safari') != -1) {
		if (agt.indexOf('version/3') == -1) {
		    if (agt.indexOf('version/4') == -1) {
                gotoURL('getFirefox.php','');
		    }
		}
	}
 }

 /****************************************************************
 *  Function to copy data to clipboard
 ***************************************************************/
function copyToClipboard(text2copy) {
  if (window.clipboardData) {
    window.clipboardData.setData("Text",text2copy);
  } 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="rsrc/_clipboard.swf" FlashVars="clipboard='+escape(text2copy)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopier).innerHTML = divinfo;
  }
}



