/**
 * @author: Mobus developement team
 * @copyright: Mobus Co., Ltd.
 * @package: WOS Application library (Private beta only)
 * @license: Mobus Co., Ltd.
 * @url: http://www.mobus.co.th
 * @version: 1.01
 * @dependencies prototype.js
 * @Revision 2, Complete 
 * @since:	2008/06/23
 * Release note: 	1. Refractor xDomain script to ScriptInjector script (prevent IECache + counter)
 * 								2. new validate email script
 * 								3. Add lmage Loader
 */

var gAuthority = false;
var gAnonymous = true;

function isAnonymous() {																						// for musicdisplay, videodisplay, photodisplay, userprofile. Other use 'checkUserAuthority'
	if ((window.myUserId == "") || (window.myUsername == "")) {
		gAnonymous = true;
		return true;
	} else {
		gAnonymous = false;
		return false;
	}
}

function checkUserAuthority() {
	if((myUsername == pUsername) && (myUserId == pUserId)) {	
		gAuthority = true;
	}
}

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    }
    else {
        return document[movieName];
    }
}

function isNullValue(s) {
	if (s == "") {
		return true;
	} else {
		return false;
	}
}

function filterInputValue(s) {
	s = s.strip();
	s = s.stripScripts().stripTags();
	s = s.escapeHTML();
	return s;
}

function encodeAjaxUrl(apiName) {
	var defaultPath = '/website/jsapi/v1/';
	var defaultExt = '.ajax';
	var apiUrl = defaultPath + apiName + defaultExt;
	return apiUrl;
}

function encodeAjaxParamUrl(apiName, paramName, paramValue) {
	var defaultPath = '/website/jsapi/v1/';
	var defaultExt = '.ajax';
	var apiUrl = defaultPath + apiName + defaultExt + '?' + paramName + "=" + paramValue;
	return apiUrl;
}


/******* highlight navigator  *******/

function setHeaderNavigator() {
	var currUrl = window.location.href;
	if (currUrl == "http://www.thewos.com/website/home.wos") {
		$("nav-home").addClassName("headerActive");
	} else if (currUrl == "http://www.thewos.com/website/people/home.wos") {
		$("nav-people").addClassName("headerActive");
	} else if (currUrl == "http://www.thewos.com/website/music/home.wos") {
		$("nav-music").addClassName("headerActive");
	} else if (currUrl == "http://www.thewos.com/website/groups/home.wos") {
		$("nav-groups").addClassName("headerActive");
	} else if (currUrl == "http://www.thewos.com/website/contests/home.wos") {
		$("nav-contest").addClassName("headerActive");
	} else if (currUrl == "http://www.thewos.com/website/videos/home.wos") {
		$("nav-videos").addClassName("headerActive");
	} else if (currUrl == "http://www.thewos.com/website/photos/home.wos") {
		$("nav-photos").addClassName("headerActive");
	} 
}

/*****  Decode/Encode text renderer ******/
function decodeHTML(s) {
	var m1 = s.replace(/&nbsp;/g, " ");
	var m2 = m1.replace(/<br\/>/g, "\n");
	var m3 = m2.replace(/<br>/g, "\n");
	return m3;
}
		
function encodeHTML(s) {
	if (s == '' || s == undefined) {
		return s;
	}
	// s = s.escapeHTML();			// temporary disable this line, due to execute html markup
	var text = '';
	var count = s.length;
	var chNext = 0;
	for (var i = 0; i < count; i++) {
		var c = s.charAt(i);
		if (i < count - 1) {
			chNext = s.charAt(i + 1);
		} else {
			chNext = 0;
		}
		if (c == ' ') {
			if (chNext != ' '){
				c = " ";
			} else {
				c = "&nbsp;";
			}
		} else if (c == '\n') {
			c = "<br/>";
		} 
		text = text + c; 
	}
	
	/* regEx [Test]
	 * extract img tag 
	 */
	/*
	var _imgTag = /<img([^<>+]*[^\/])>/;
	var _imgSrc = /src=(.+?[\.jpg|\.gif]")/;
	var x = text.match(_imgSrc); 
	if (x != null){
		var _newImg = "<br /><a href=" + x[1] + "><img src=" + x[1] + " width=\"480px\" style=\"border: 1px solid #333333;margin: 5px 0px;\" /></a><br />";
		text += _newImg;
	}
	*/
	
	return text;
}


function renderDateTime(s) {
	if ((s != "") && (s != "N/A")) {
		var dt = s;
		dt = parseFloat(dt);
		dt = new Date(dt);
		var localeDate = dt.toLocaleDateString();
		var localeTime = dt.toLocaleTimeString();
		var hh = parseInt(dt.getHours());
		var mm = parseInt(dt.getMinutes());
		if (hh < 10) {
			hh = '0' + hh;
		}
		if (mm < 10) {
			mm = '0' + mm;
		}
		return localeDate + " " + hh + ':' + mm;
	} else {
		return "N/A";
	}
}

function renderDate(s) {
	var dt = s;
	dt = parseFloat(dt);
	dt = new Date(dt);
	var localeDate = dt.toLocaleDateString();
	return localeDate;
}

function renderTime(s) {
	if ((s != "") && (s != "N/A")) {
		var dt = s;
		dt = parseFloat(dt);
		dt = new Date(dt);
		var hh = parseInt(dt.getHours());
		var mm = parseInt(dt.getMinutes());
		if (hh < 10) {
			hh = '0' + hh;
		}
		if (mm < 10) {
			mm = '0' + mm;
		}
		return hh + ':' + mm;
	} else {
		return "N/A";
	}
}

function decodeJSON(s) {
	var sJSON = s.strip();
	if (sJSON.substr(0,2) == "/*") {
		sJSON = sJSON.substring(2, sJSON.length - 2);
	}
	var json = eval('('+ sJSON +')');
	var jsonLogin = json["login"];
	var jsonType = typeof jsonLogin;
	if (jsonType == 'object') {
		window.location = json.login.url;
	} else {
		return json;
	}
}


function normalizeShortText(s, n) {
	var ms = s;
	ms = ms.truncate(n);
	return ms;
}

function textCounter(field, cntField, limit) {
	if (field.value.length > limit) {
		field.value = field.value.substring(0, limit);
	} else {
		cntField.value = limit - field.value.length;
	}	
}

/****** skill encoder/decoder ******/
var skillCollection = [];

function parseSkill(ss) {
	var sLength = ss.length;
	var n = sLength/4;
	var x = ss.substr(0,4);
	var x = x.substr(0,2);
	skillCollection.push(x);
	for (var i=0; i<(n-1); i++) {
		ss = ss.substring(4);
		x = ss.substr(0,4);
		x = x.substr(0,2);
		skillCollection.push(x);
	}
	var totalSkill = renderSkill();
	return totalSkill;
}

function renderSkill() {
	var skills = '';
	var allSkill = skillCollection;
	for (var i = 0; i <(allSkill.length); i ++) {
		skills += isSkill(allSkill[i]);
		if (i < (allSkill.length-1)) {
			skills += ', ';
		} 
	}
	skillCollection = [];
	return skills;
}

function isSkill(s) {
	if (s == '01') {
		return 'Vocal Performer';
	} else if (s == '02') {
		return 'Musician';
	} else if (s == '03') {
		return 'Dancer';
	} else if (s == '04') {
		return 'Film Maker';
	} else if (s == '05') {
		return 'Photographer';
	} else if (s == '06') {
		return 'Pretty/MC';
	} else if (s == '07') {
		return 'IT Professional';
	} else if (s == '08') {
		return 'Comedian';
	} else if (s == '09') {
		return 'Reporter';
	} else {
		return 'N/A';
	}
}
/*
function joinUs() {
	var gJoinDlg = new Control.Modal(false, {
		containerClassName: 'beta',
		width: 550,
		height: 300,
		fade: true, 
		overlayOpacity: 0.75, 
		overlayCloseOnClick: true,
		contents: function() {
			return '<a href="javascript:closeJoinBox();"><div id="signUpBeta"></div></a>';
		}
	});
	gJoinDlg.open();
}

function closeJoinBox() {
	Control.Modal.close();
}
*/

/*** mobile number renderer ***/
var codeCollection = [];						// TODO: clear collection

function renderMobileNumber(oCode, cCode, digit) {	
	var allCode = oCode + cCode;
	var n = allCode.length/digit;
	var x = allCode.substr(0,digit);
	codeCollection.push(x);
	for (var i = 0; i < (n-1); i++) {
		allCode = allCode.substring(digit);
		x = allCode.substr(0,digit);	
		codeCollection.push(x);
	}
	var code = renderMobileCode();
	return code;
} 

function renderMobileCode() {
	var color = ['#FF0099','#000000','#0099FF','#000000','#FF0099','#000000','#0099FF']
	var code = '';
	var _codeCollection = codeCollection;
	for (var i = 0; i <(_codeCollection.length); i ++) {
		code += '<span style="color:' + color[i]+ '">' + _codeCollection[i] +'</span>';
	}
	codeCollection = [];
	return code;
}

/*******  Web Access #TODO:  *******/

var gTimeout;
var gSessionid = '';

function initWebAccessCookie(t, id) {
	var cId = ''; 
	if (t == 'profile') {
		cId = 'thewos_userid' + id;
	} else if (t == 'audio') {
		cId = 'thewos_audioid' + id;
	} else if (t == 'video') {
		cId = 'thewos_videoid' + id;
	} else if (t == 'photo') {
		cId = 'thewos_photoid' + id;
	}
	var jc = readSessionCookie('JSESSIONID');
	var tc = readProfileCookie(cId);
	if ((!tc) && (tc != jc)) {		
		collectWebAccess(t, id);
		gSessionid = jc;
	} 
} 

function createWebAccessCookie(t, id) {
	var cId = ''; 
	if (t == 'profile') {
		cId = 'thewos_userid' + id;
	} else if (t == 'audio') {
		cId = 'thewos_audioid' + id;
	} else if (t == 'video') {
		cId = 'thewos_videoid' + id;
	} else if (t == 'photo') {
		cId = 'thewos_photoid' + id;
	}
	
	var expiretime = 30;				// minutes
	var exTime = new Date();				
	exTime.setTime(exTime.getTime()+(expiretime*60*1000));
	var x = new Date();
	x.setTime(x.getTime());
	document.cookie = cId + "=" + gSessionid + ";"+((expiretime==null) ? "" : ";expires="+ exTime.toGMTString()) + "path=/website";
}

function readProfileCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function readSessionCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) {
			return c.substring(nameEQ.length,c.length);	
		}
	}
	return null;
}

/***** *****/
var gWebAccessType;
var gWebAccessId;

function collectWebAccess(t, id) {
	gWebAccessType = t;
	gWebAccessId = id;	
	if (gWebAccessType == 'nodirectprofile') {
		setTimeout('startCollectWebAccess()', 5000);
	} else if (gWebAccessType == 'directprofile') {
		setTimeout('startCollectWebAccess()', 5000);
	} else if (gWebAccessType == 'photo') {
		setTimeout('startCollectWebAccess()', 100);
	} else {
		startCollectWebAccess();
	}
}

function startCollectWebAccess() {
	var url = '';
	var up = this;
	var dtRf = new Date().getTime();
	if (gWebAccessType== 'nodirectprofile') {
		url = encodeAjaxParamUrl('collectProfileWebAccess', 'rf',dtRf);
		url += '&userId=' + gWebAccessId;
	} else if (gWebAccessType == 'directprofile') {
		url = encodeAjaxParamUrl('collectDirectProfileWebAccess', 'rf', dtRf);
		url += '&userId=' + gWebAccessId;
	} else if (gWebAccessType == 'audio') {
		url = encodeAjaxParamUrl('collectAudioWebAccess', 'rf',dtRf);
		url += '&audioId=' + gWebAccessId;
	} else if (gWebAccessType == 'video') {
		url = encodeAjaxParamUrl('collectVideoWebAccess', 'rf',dtRf);
		url += '&videoId=' + gWebAccessId;
	} else if (gWebAccessType == 'photo') {
		url = encodeAjaxParamUrl('collectPhotoWebAccess', 'rf',dtRf);
		url += '&photoId=' + gWebAccessId;
	}
	if (window.pUserId != window.myUserId) {
		var wosAjax = new Ajax.Request(url, {
			method: 'post',
			parameters: '',
			onComplete: function(transport) {
				var sJSON = transport.responseText;
				var json = window.decodeJSON(sJSON);
				if (json.notification.summary.type=="ERROR") {					
				} else if(json.notification.summary.type=="INFO") {
				}
			}, 
			onFailure: function(error) {
			}
		});
	}
}

function requestPageCompleteWithError(data) {
	var errorValue = data;
	alert(window.glm_ajax_reportDataError + ": " + errorValue);
}

function requestPageFailure(error) {
	var errorValue = error;
	alert(window.glm_ajax_reportError + ": " + errorValue);
}

Event.observe(window, 'load', function() {
  $$('a[href^=#]:not([href=#])').each(function(element) {
    element.observe('click', function(event) {
      new Effect.ScrollTo(this.hash.substr(1));
      Event.stop(event);
    }.bindAsEventListener(element))
  })
})


function fbShare() {
	var u = location.href;
	var t = document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}

Event.observe(window, 'load', setHeaderNavigator, false);