/******************** image ********************/
function fncoverImg(imgObj) {
    var imgSrc = imgObj.src;
    var ext;
    var name;
    var scanName;

    ext = imgSrc.substring(imgSrc.lastIndexOf("."));
    name = imgSrc.substring(0, imgSrc.lastIndexOf("."));

    if (name.lastIndexOf("_over") > 0) {
        name = name.substring(0, name.indexOf("_over"));
    }
    imgObj.src = name + "_over" + ext;
}

function fncoutImg(imgObj) {
    var imgSrc = imgObj.src;
    var ext;
    var name;

    ext = imgSrc.substring(imgSrc.lastIndexOf("."));

    if(imgSrc.lastIndexOf("_over") < 0) {
        name = imgSrc.substring(0, imgSrc.lastIndexOf("."));
    }
    else {
        name = imgSrc.substring(0, imgSrc.lastIndexOf("_over"));
    }
    imgObj.src = name + ext;
}

function fncDocRating(num) {
    var imgSrc = document.getElementById("star"+num).src;
    var ext;
    var name;
    var scanName;
    ext = imgSrc.substring(imgSrc.lastIndexOf("."));
    name = imgSrc.substring(0, imgSrc.lastIndexOf("."));

	if (name.lastIndexOf("_over") > 0)
		name = name.substring(0, name.indexOf("_over"));
	for (var i=1; i < 6; i++) {
		if (i <= num)
			document.getElementById("star"+i).src = name + "_over" + ext;
		else
			document.getElementById("star"+i).src = name + ext;
	}
	var desc=new Array();
	desc[1] = "<p class='text_14 bold'>"+lang["rateStart11"]+": <span class='fc_point'>"+lang["rateStart12"]+"</span></p>";
	desc[2] = "<p class='text_14 bold'>"+lang["rateStart21"]+": <span class='fc_point'>"+lang["rateStart22"]+"</span></p>";
	desc[3] = "<p class='text_14 bold'>"+lang["rateStart31"]+": <span class='fc_point'>"+lang["rateStart32"]+"</span></p>";
	desc[4] = "<p class='text_14 bold'>"+lang["rateStart41"]+": <span class='fc_point'>"+lang["rateStart42"]+"</span></p>";
	desc[5] = "<p class='text_14 bold'>"+lang["rateStart51"]+": <span class='fc_point'>"+lang["rateStart52"]+"</span></p>";
	document.getElementById("actionComment2").innerHTML =  desc[num];
}

/******************** Check Form (SignUp/Edit Profile) ********************/

function fncChkKeywordLength(t,v) {
    if (v.length < 2) {
        alert(lang["msgInvalidKeyword"]);
    } else {
        t.submit();
        return false;
    }
}

function searchProfile(){
    var theKeywords = document.getElementById("profileSearchText").value;
    if(theKeywords == '')
        alert(lang["msgInvalidKeywordP"]);
    else
        document.all.profileSearchForm.submit();
    return false;
}

function checkEnter(e){
    if(e.keyCode == 13){
        searchProfile();
        return false;
    }
}

function fncIsEmail(email) {
    var invalidChars = " /:,;"
    for (i=0; i<invalidChars.length; i++) {	// does it contain any invalid characters?
        badChar = invalidChars.charAt(i);
        if (email.indexOf(badChar) > -1) return false;
    }
    atPos = email.indexOf("@",1);	// there must be one "@" symbol
    if (atPos == -1) return false;
    if (email.indexOf("@",atPos+1) != -1) return false;	// and only one "@" symbol
    periodPos = email.indexOf(".",atPos);
    if (periodPos == -1) return false;	// and at least one "." after the "@"
    if (periodPos+3 > email.length) return false;	// must be at least 2 characters after the "."
    return true;
}

function fncChkEmail(pm_sEmail) {
    var invalidChar = '';
    var oneChar = '';
    for(var i=0; i<pm_sEmail.length; i++) {
		oneChar = pm_sEmail.charAt(i);
		if(oneChar=='#' || oneChar==':' || oneChar=='*' || oneChar=='?' || oneChar=='<' || oneChar=='>' || oneChar=='|' || oneChar=='%' || oneChar=='+' || oneChar=='"' || oneChar=='\'' || oneChar=='~' || oneChar=='&') {
			invalidChar = pm_sEmail.charAt(i);
			break;
      }
    }
    if(invalidChar!='') {
		alert("'"+invalidChar+"'" +lang["msgInvalidEmail1"]);
		return false;
	} else {
		return true;
    }
}

function fncChkPwd(pm_sPwd){
    if (pm_sPwd.length < 6) {
		alert(lang["msgInvalidPwd1"]);
		return false;
    }
    if (pm_sPwd.length > 10) {
		alert(lang["msgInvalidPwd2"]);
		return false;
    }
     for (i=0; i <= pm_sPwd.length; i++) {
		if (IsWhite (pm_sPwd.charAt(i)) ){
			alert (lang["msgInvalidPwd3"]);
			return false;
		}
	}
	return true;
}

function fncChkWhite(pm_Text){
	for (i=0; i <= pm_Text.length; i++) {
		if (IsWhite (pm_Text.charAt(i)) ){
			alert (lang["msgInvalidPwd4"]);
			return false;
		}
	}
	return true;
}

function IsWhite ( arg_ch ){
    if ( arg_ch == '\t' || arg_ch == ' ' || arg_ch == '\n' )
          return  true
    else  return  false
}

function fncTrim(str)
{
    var TRIM_PATTERN = /(^\s*)|(\s*$)/g;
    return str.replace(TRIM_PATTERN, "");
}

function fncChkName() {
   if($F('name').length < 4 || $F('name').length > 10) return false;
   for(var i = 0; i < $F('name').length; i++) {
      var chr = $F('name').substr(i,1);
      if((chr < '0' || chr > '9') && (chr < 'a' || chr > 'z')) return false;
   }
   return true;
}

function isValidDay(yyyy, mm, dd) {
    var m = parseInt(mm,10) - 1;
    var d = parseInt(dd,10);
    var end = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
    if ((yyyy % 4 == 0 && yyyy % 100 != 0) || yyyy % 400 == 0) {
       end[1] = 29;
    }
    return (d >= 1 && d <= end[m]);
}

function chkFrmProfilePrivate(){

    var birthm = document.getElementById("birthMonth");
    var birthd = document.getElementById("birthDay");
    var birthy = document.getElementById("birthYear");

    if (birthm.value || birthd.value || birthy.value )
    {
        if (!birthm.value) { alert('Select your birth day :: Month'); birthm.focus(); return false; }
        if (!birthd.value) { alert('Select your birth day :: Day'); birthd.focus(); return false; }
        if (!birthy.value) { alert('Select your birth day :: Year'); birthy.focus(); return false; }
    }
    else if (!document.getElementById("ccode").value) {
         alert('Select your Country'); document.getElementById("ccode").focus(); return false;
    }

    if (isValidDay(birthy.value, birthm.value, birthd.value) == false) {
        alert('Invailid day. Select correct day'); birthd.focus(); return false;
    }

    return true;
}

/******************** change Country Code Value ********************/

function chgccode () {
	var ccode = document.getElementById("select_ccode").value;
	document.getElementById("ccode").value = ccode;
}

/******************** check comment string size *********************/

function setStringLength() {
	var lm_oComments = document.getElementById("cmtStory").value;
	if(lm_oComments.length > 600) {
		lm_oComments = lm_oComments.substring(0,600);
		document.getElementById("cmtStory").value = lm_oComments;
	}

	document.getElementById("cmtStrSize").innerHTML = lm_oComments.length;
}

/******************** check comment string (10 more) *********************/

function chkCommentFrm() {
	if ($F('cmtStory').length<10) {
		alert(lang["msgValidCmt10more"]);
		$('cmtStory').focus();
		return false;
	}

	var cnt_cnt = $F('cmtStory').length;
	var cnt_w = 0;
	for (i=0; i <= $F('cmtStory').length; i++) if (IsWhite ($F('cmtStory').charAt(i))) cnt_w++;
	if (((cnt_w/cnt_cnt)*100) > 50)
	{
		alert (lang["msgValidCmtSoManySpaces"]);
		$('cmtStory').focus();
		return false;
	}
    return true;
}

/******************** copy text to clipboard  http://webchicanery.com/2006/11/14/clipboard-copy-javascript/ *********************/
function copyToClipboard(text2copy) {
	if (window.clipboardData) {
		window.clipboardData.setData("Text",text2copy);
		alert(lang["msgCopyUrl1"] + "\n\n"+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="/tools/copyToClipboard.swf" FlashVars="clipboard='+encodeURIComponent(text2copy)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		document.getElementById(flashcopier).innerHTML = divinfo;
		alert(lang["msgCopyUrl2"] + "\n\n"+text2copy);
	}
}

function notYet() {
	alert("This fuction is not available...");
}

function goDocsUrl(obj) {
	var dsn = obj.value;
	location.href = '/docs/view.php?dsn='+dsn;
}

function goPortfolioUrl(obj) {
	var psn = obj.value;
	location.href = '/portfolio/view.php?psn='+psn;
}

function click_html_view(url){
	var lastIndexOfSlash = url.lastIndexOf('/');

	var dsn = url.substr(lastIndexOfSlash+1);

	var lastIndexOfDot2 = dsn.lastIndexOf('=');

	if(lastIndexOfDot2 > 0){
		dsn = dsn.substr(lastIndexOfDot2+1);
    }else{
		var lastIndexOfDot = dsn.lastIndexOf('.');
		if(lastIndexOfDot > 0){ dsn = dsn.substr(0, lastIndexOfDot); }
	}

	var js_targetURL = "/docs/popup.php?dsn="+dsn;
	if(js_targetURL == null || js_targetURL == ""){
		alert(lang["msgConvInProgress"]);
	}else{
		window.open(js_targetURL);
	}
	//Lightbox.hideBox();
}

function click_power_view(url){
	var js_targetURL = url;
	if(js_targetURL == null || js_targetURL == ""){
		alert(lang["msgNeedSigninPV"]);
	}else{
		window.open(url);
	}
}

function click_showfx_view(url){
    var js_targetURL = url;
    if(js_targetURL == null || js_targetURL == ""){
        alert(lang["msgNeedSigninPV"]);
    }else{
        window.open(url);
    }
}


function URLEncode(plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '"
                        + ch
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};

function URLDecode(encoded)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef";
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2)
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
};

document.getElementsByClassName2 = function(className)
{   var outArray = new Array();
    var item;
    try {
        var xpathResult = document.evaluate('//*[@class = "' + className + '"]', document, null, 0, null);
        while (item = xpathResult.iterateNext())
            outArray[outArray.length] = item;
    }
    catch(err) {
        // ie fix
        var currentIndex = 0;
        var allElements = document.getElementsByTagName('*');
        for(var i=0; i < allElements.length; i++)
        {   if(allElements[i].className.match(className))
            {   outArray[currentIndex] = allElements[i];
                currentIndex++;
            }
        }
    }
    return outArray;
}

switchDocListClass = function (num) {

    if (num == 2) {
        setDisplayMode(2);
        var blocks = document.getElementsByClassName2("docListActionMsgBoxClass");
        var count = blocks.length;
        for (i=0; i<count;i++) {
            blocks[i].style.display = "none";
        }
    } else if (num == 3) {
        setDisplayMode(3);
    } else {
        setDisplayMode(1);
    }

    document.getElementById("classDisplayDD1").className = "";
    document.getElementById("classDisplayDD2").className = "";
    document.getElementById("classDisplayDD3").className = "";
    var c = document.getElementById("innerList");
    for (ii=0; ii<c.childNodes.length; ii++)
    {
        var c2 = c.childNodes[ii];

        if (c2.className == "docListItem" || c2.className == "docListItemT" || c2.className == "docListItemTT")
        {
            if (num == 2)
            {
                // alert(ii+"::"+c2.className);
                c2.className = "docListItemT";
                document.getElementById("classDisplayDD2").className = "filter_on";
                // alert(document.getElementById("innerList").style.display);
            }
            else if (num == 3)
            {
                c2.className = "docListItemTT";
                document.getElementById("classDisplayDD3").className = "filter_on";
            }
            else
            {
                c2.className = "docListItem";
                document.getElementById("classDisplayDD1").className = "filter_on";
            }
        }
    }
}

function setDisplayMode(m) {
    var url = "/ajax/main_setDisplayMode.php";
    var paras = "displayMode="+m;
    var setDisplayModeAjax = new Ajax.Request( url, { method: 'get', parameters: paras });
}


/***********************************************************************
* common ajax library. (if can... for all ajax tools)
***********************************************************************/

var ajaxLib = {

    action : function (mode, options, frmMethod, progressID) {
        if (options.split("&")[0].split("=")[0] == "action") {
            if (options.split("&")[0].split("=")[1] == "del")
            {
                var answer = confirm(lang["confirmReallyDo"]);
                if (!answer)
                    return false;
            }
        }
        if (mode == "memberListItem")
            var chkUrl = "/_library/ajax/profiles.php";
        else
            var chkUrl = "/_ajax/rating.php";

        var params = "mode=" + mode + "&" + options;
        new Ajax.Updater(
            { success: "ajaxTempArea" },
            chkUrl,
            {
                evalScripts:true,
                asynchronous: true,
                method: frmMethod,
                parameters: params,
                onLoading: function(request)  {
                    if (progressID != 0)
                        Element.show(progressID);
                },
                onComplete: function(request) {
                    if (progressID != 0)
                        Element.hide(progressID);
                },
                onFailure : reportError
            }
        );
    },

    closeDiv : function(e) {
        e.remove();
    }
}

/******************** prototype updater ********************/

    function submitEmailBox(dsn){
        var str = Form.serialize("emailForm"+dsn);
        var tmp = str.split("&");
        var tmp2 = tmp[0].split("=");
        var e = URLDecode(tmp2[1]);

        if (!fncIsEmail(e)) {
            alert(lang["msgInvalidEmail2"]); return false;
        } else if (!fncChkEmail(e)) {
            return false;
        } else {
            docListActionAjax('email2', dsn, str);
        }
        return false;
    }

    function submitEmailBox2(dsn){
        var str = Form.serialize("emailForm"+dsn);
        var tmp = str.split("&");
        var tmp2 = tmp[0].split("=");
        var e = URLDecode(tmp2[1]);

        if (!fncIsEmail(e)) {
            alert(lang["msgInvalidEmail2"]); return false;
        } else if (!fncChkEmail(e)) {
            return false;
        } else {
            profilesActionAjax('pfDocEmail2', dsn, 0, str);
        }
        return false;
    }

    function submitAdd2PortfolioBox(dsn){
        var targetFrm = "add2PortfolioForm"+dsn;
        var str = Form.serialize(targetFrm);
        var tmpPsn = str.split("=");
        var psn = tmpPsn[1];

        if (psn == "") {
            alert(lang["newPortfolioMgs6"]); return false;
        } else {
            var str = "psn="+psn;
            docListActionAjax('add2Portfolio2', dsn, str);
        }
        return false;
    }

    function submitAdd2PortfolioBoxInView(dsn){
        var targetFrm = "add2PortfolioForm";
        var str = Form.serialize(targetFrm);
        var tmpPsn = str.split("=");
        var psn = tmpPsn[1];

        if (psn == "") {
            alert(lang["newPortfolioMgs6"]); return false;
        } else {
            var str = "psn="+psn;
            actAjaxView('add2Portfolio', dsn, 0, psn);
        }
        return false;
    }

function submitAdd2GroupBox(target_id, target_type, tmp, msg){
	var targetFrm = "add2GroupForm"+target_id;
	var str = Form.serialize(targetFrm);

	var tmpGsn = str.split("=");
	var gsn = tmpGsn[1];

	if (gsn == "") {
		alert(lang["gropsFormChekMgs6"]); return false;
	} else {
		var str = "gsn="+gsn;
		listActionAjax('add2Group2', target_id, target_type, 'groups', tmp, msg, str);
	}
	return false;
}

// Doc List Ajax Action
function docListActionAjax(mode, dsn, str) {
	var chkUrl = "/docs/docListAction.php";
    var paras = "mode="+mode+"&dsn="+dsn+"&"+str;

    var targetProgress = 'progress'+mode+dsn;
    var tmpDiv = "docListActionMsgBoxTmp"+dsn;
    var msgDiv = "docListActionMsgBox"+dsn;

    new Ajax.Updater(
        { success: tmpDiv },
        chkUrl,
        {
        evalScripts:true,
        asynchronous: true,
        method: "get",
        parameters: paras,
        onLoading: function(request)  {
            Element.show(targetProgress);
            document.getElementById(msgDiv).innerHTML = "";
            document.getElementById(msgDiv).style.display = "none";
        },
        onComplete: function(request) {
            Element.hide(targetProgress);
            new Effect.Appear(document.getElementById(msgDiv));
        },
        onFailure : reportError
        }
    );
}

// Doc List Ajax Action
// target_id : dsn, psn, usn, gsn
// target_type : docs :1, portpolios:2, message:3
// type : docs, portpolios, groups
function listActionAjax(mode, target_id, target_type, type, tmp, msg, str) {
	var chkUrl = "/groups/action.php";
	var paras  = "mode="+mode+"&target_id="+target_id+"&target_type="+target_type+"&"+str;

    if(mode == 'add2Group2'){
         pmode = 'add2Group';
	}else{
         pmode = mode;
	}
    var targetProgress = 'progress'+pmode+target_id;
    var tmpDiv = tmp+target_id;
    var msgDiv = msg+target_id;

    new Ajax.Updater(
        { success: tmpDiv },
        chkUrl,
        {
        evalScripts:true,
        asynchronous: true,
        method: "get",
        parameters: paras,
        onLoading: function(request)  {
            Element.show(targetProgress);
            document.getElementById(msgDiv).innerHTML = "";
			document.getElementById(msgDiv).style.display = "none";
        },
        onComplete: function(request) {
            Element.hide(targetProgress);
            new Effect.Appear(document.getElementById(msgDiv));
        },
        onFailure : reportError
        }
    );
}

// Doc, Portfolio Detail page Ajax Action
function actAjaxView(mode, p1, p2, p3) { // actAjaxView(mode, p1::dsn, p2::type(doc(1)/portfolio(2)), p3::rate(1~5)/)
	var chkUrl = "action.php";
	if (mode == "packing")
	{
		var Obj = document.getElementsByName("sel_portfolio[]");
		var isChecked = 0;
		var psn = new Array();
		for (var ii=0; ii<Obj.length; ii++) {
			if (Obj[ii].checked == true) {
				psn[isChecked] = Obj[ii].value;
				isChecked++;
			}
		}
		if (isChecked == 0) { alert('Please check at least one portfolio'); return false; }
		p2 = psn.join("::");
	}
	else if (mode == "createPortfolio")
	{
		if ($F("portfolioTitle") == "") { alert('Please type portfolio title'); $('portfolioTitle').focus(); return false;}
		if ($F("portfolioTitle").length<5) { alert('Portfolio title must be at least 5 characters.'); $('portfolioTitle').focus(); return false;}
		if ($F("portfolioSummary") == "") { alert('Please type portfolio summary'); $('portfolioSummary').focus(); return false;}
		if ($F("portfolioSummary").length<5) { alert('Portfolio summary must be at least 5 characters.'); $('portfolioSummary').focus(); return false;}
		p2 = document.getElementById("portfolioCategory").value + "::" + document.getElementById("portfolioTitle").value;
		p3 = $F("portfolioSummary");
	}
    else if (mode == "email")
	{
		if (!fncIsEmail($F("emailTo"))) { alert(lang["msgInvalidEmail2"]); $('emailTo').focus(); return false; }
        if ($F("emailTo") == "") { alert(lang["msgValidNeedEmail"]); $('emailTo').focus(); return false;}
        if ($F("emailSubject") == "") { alert(lang["msgValidNeedSubject"]); $('emailSubject').focus(); return false;}
        if (fncChkEmail($F("emailSubject")) == false) { return false; }
		p2 = $F("emailTo");
		p3 = $F("emailSubject");
	}

	var paras = "mode=" + mode + "&p1=" + p1 + "&p2=" + p2 + "&p3=" + p3;
	new Ajax.Updater(
		{ success: 'actionMessage' },
		chkUrl,
		{
		evalScripts:true,
		asynchronous: true,
		method: "get",
		parameters: paras,
		onLoading: function(request)  {
			Element.show('progress'+mode);
			document.getElementById("actionMessage").innerHTML = "";
			document.getElementById("actionMessage").style.visibility = "visible";
		},
		onComplete: function(request) {
			Element.hide('progress'+mode);
			Effect.Appear(document.getElementById('actionMessage'));
			window.setTimeout("document.getElementById('actionMessage').innerHTML='';",5000);
		},
		onFailure : reportError
		}
	);
}

// Doc, Portfolio Comment action
function actAjaxCmt(theForm,m,type) {
	if ($F('cmtStory').length<10) {
		alert(lang["msgValidCmt10more"]);
		$('cmtStory').focus();
		return false;
	}

	var cnt_cnt = $F('cmtStory').length;
	var cnt_w = 0;
	for (i=0; i <= $F('cmtStory').length; i++) if (IsWhite ($F('cmtStory').charAt(i))) cnt_w++;
	if (((cnt_w/cnt_cnt)*100) > 50)
	{
		alert (lang["msgValidCmtSoManySpaces"]);
		$('cmtStory').focus();
		return false;
	}

	var chkUrl = "/"+ type + "/action.php";
	document.getElementById("cmtMode").value = m.value;
	var paras = Form.serialize($(theForm));

	new Ajax.Updater(
		{ success: 'actionCmtMessage' },
		chkUrl,
		{
		evalScripts:true,
		asynchronous: true,
		method: "post",
		parameters: paras,
		onLoading: function(request)  {
			Element.show('progresscomment');
			document.getElementById("actionCmtMessage").innerHTML = "";
			document.getElementById("actionCmtMessage").style.visibility = "visible";
			document.getElementById("actionCmtMessage").style.display = "block";
		},
		onComplete: function(request) {
			Element.hide('progresscomment');
			// new Effect.Appear(document.getElementById('actionCmtMessage'),{duration: 5});
		},
		onFailure : reportError
		}
	);
}

/* Ajax Error */
function reportError() {
    alert("unknown error");
}


function CopytoMyFolder_Popup(sys_email, dsn)
{
     window.open('/docs/cp2myfolder_popup.php?sys_email='+sys_email+'&dsn='+dsn,'popup','width=650, height=250, toolbar=no, menubar=no, scrollbars=no, resizable=no') ;
}

function switchThumb(e) {
    if (e.checked == true)
    {
        $("thumbs").disabled = true;
        $("thumbs").value = "";
        if ($(e).getAttribute("id") == "isImageDefault")
            var aaa;
            // $("isImageDoNotUse").checked = false;
        else
            $("isImageDefault").checked = false;
    }
    else
    {
        $("thumbs").disabled = false;
    }
}

/****************** Docs ajax library *******************/

    DOCS_AJAX  = {
        replace : function (id, pageUrl, targetProgress) {
            new Ajax.Updater(
                { success: id },
                pageUrl,
                {
                evalScripts:true,
                asynchronous: true,
                method: "get",
                parameters: '',
                onLoading: function(request)  {
                    Element.show(targetProgress);
                    /*document.getElementById(msgDiv).innerHTML = "";*/
                    /*document.getElementById(msgDiv).style.display = "none";*/
                },
                onComplete: function(request) {
                    Element.hide(targetProgress);
                    /*new Effect.Appear(document.getElementById(msgDiv));*/
                },
                onFailure : reportError
                }
            );
        }
    }

/****************** String Cut by Pixel *******************/
strCutbyPx = {

    getStr : function (e) {
        if (e.innerText) return e.innerText; // IE 6,7/Opera
        if (e.textContent) return e.textContent; // FF
        return e.innerHTML.replace(/<\/?[^>]+>/gi,"");
    },

    setStr : function (e, text) {
        if (e.innerText) { e.innerText = text; return; }
        if (e.textContent) { e.textContent = text; return; }
        while (e.firstChild)
            e.removeChild(e.firstChild);
        e.appendChild(document.createTextNode(text), e.childNodes[0]);
    },

    strCut : function (e, length, suffix) {
        var str = this.getStr(e);
        var len;
        if (!str || !(len = str.length))
            return;
        e.style.whiteSpace = "nowrap";
        e.style.textOverflow = "ellipsis"; //IE
        e.style.overflow = "hidden";
        if (e.style.display != "inline")
            e.style.display = "inline";

        var width = e.offsetWidth;
        if (!width || width < length - 8)
            return;
        var temp = length;
        if (suffix)
        {
            e.innerHTML += suffix;
            length -= (e.offsetWidth - width + 4);
            if (length < 0)
                return;
        }
        else
            suffix = "";
        e.title = str;
        e.alt = str;

        var cut = parseInt(length / (width / len)) + 1;
        this.setStr(e, str.substr(0, cut));
        if (e.offsetWidth > length)
        {
            while (--cut)
            {
                this.setStr(e, str.substr(0, cut).replace(/(\s*$)/g, ""));
                if (e.offsetWidth < length)
                    break;
            }
        }
        else
        {
            while (cut++ < len)
            {
                this.setStr(e, str.substr(0, cut));
                if (e.offsetWidth > length)
                {
                    this.setStr(e, str.substr(0, cut - 1).replace(/(\s*$)/g, ""));
                    break;
                }
            }
        }
        e.innerHTML += suffix;
    },

    allStrCut : function (className) {
        var classArray = document.getElementsByClassName(className); // prototype
        var classArrayCount = classArray.length;
        for (i=0; i<classArrayCount;i++) {
            var classArrayLength = parseInt($(classArray[i]).getAttribute('strLength'));
            this.strCut (classArray[i], classArrayLength,"...");
        }
    }
}



function goToPub(dsn) {
    document.getElementById("dsn").value = dsn;
    document.getElementById("frmGoToPub").submit();
}

function goToPubPortfolio(psn) {
    document.getElementById("psn").value = psn;
    document.getElementById("frmGoToPub").submit();
}



function popUpWindow(pageUrl, winName, width, height, scroll){
    var win = null;

	LeftPosition = (screen.width) ? (screen.width-width)/2 : 0;
	TopPosition  = (screen.height) ? (screen.height-height)/2 : 0;
	settings = 'height='+height+',width='+width+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',toolbar=0,menubar=0,status=0,scrollbars=0,resizable=0';
	win = window.open(pageUrl, winName, settings);

}

/* common_footer Related link */
function goRelatedURL(selectVal){
    var goURL = "#";
    if(selectVal == 'home')
        goURL = "http://member.thinkfree.com/";
    else if(selectVal == 'nos')
       goURL = "http://member.thinkfree.com/";
    else if(selectVal == 'product')
        goURL = "http://product.thinkfree.com/";
    else if(selectVal == 'news')
        goURL = "http://product.thinkfree.com/news/";
    else if(selectVal == 'blog')
        goURL = "http://blog.thinkfree.com/";
    window.location = goURL;
}


/* popup window control */

var popup = {

    open : function (url, w, h) {
        var WindowLeft = (screen.width - w)/2;
        var WindowTop= (screen.height - h)/2;
        NewPopup = window.open(url, "NewPopup", "titlebar=0, resizable=1, scrollbars=yes, width="+w+", height="+h+", top="+WindowTop+", left="+WindowLeft);
        NewPopup.focus();
        return false;
    },

    resize : function (w,h) {
        document.body.style.overflow='hidden';
        var clintAgent = navigator.userAgent;
         if ( clintAgent.indexOf("MSIE") != -1 )
             window.resizeBy(w-document.body.clientWidth, h-document.body.clientHeight);
        else
            window.resizeBy(w-window.innerWidth, h-window.innerHeight);
        return false;
    },

    opener_refresh_close_self : function (url) {
        opener.document.location = url;
        this.close();
        return false;
    },

    opener_refresh : function () {
        opener.document.location.reload();
        return false;
    },

    close : function () {
        window.close();
        return false;
    }
}

/* popup's tools */

var Tools = {

    count_email : 0,

    chkEmailForm : function () {
        if (!$F("emails")) {
            alert(lang["msgInvalidEmail3"]);
            $("temp_email").focus();
            return false;
        }
        else
            return true;
    },

    addEmail : function () {

        if (!$F("temp_email")) {
            alert(lang["msgInvalidEmail3"]);
            $("temp_email").focus();
            return false;
        }
        else
        {
            if (fncIsEmail($F("temp_email")))
            {
                if (this.count_email > 9)
                {
                    alert(lang["msgInvalidEmail5"]);
                    return false;
                }
                else
                {
                    var emailsArray = $F("emails").split(",");
                    for ($ii=0; $ii<emailsArray.length; $ii++)
                    {

                        if (fncTrim(emailsArray[$ii]) == $("temp_email").value)
                        {
                            alert(lang["msgInvalidEmail4"]);
                            return false;
                        }
                    }
                    var prefix = ($("emails").value) ? ", " : "";
                    $("emails").value = $("emails").value + prefix +$F("temp_email");
                    $("temp_email").value = "";
                    this.count_email++;
                    return true;
                }

            }
            else
            {
                alert(lang["msgInvalidEmail2"]);
                $("temp_email").focus();
                return false;
            }
        }
    }


}

function AjaxTagsCheck(par,msg) {
	var chkUrl = "/upload/common_action.php";
	var msgDiv = msg;
	var paras  = par;
	var tmpDiv = "ajaxTempArea";
	new Ajax.Updater(
		{ success: tmpDiv },
		chkUrl,
		{
		evalScripts:true,
		asynchronous: true,
		method: "get",
		parameters: paras,
		onComplete: function(request) {
			new Effect.Appear(document.getElementById(msgDiv));
		},
		onFailure : reportError
		}
	);
}

function AjaxUrlCheck(url,msg) {
    var chkUrl = url;
    var msgDiv = msg;
    var paras ='';
 	var tmpDiv = "ajaxTempArea";
    new Ajax.Updater(
        { success: msgDiv },
        chkUrl,
        {
        evalScripts:true,
        asynchronous: true,
        method: "get",
        parameters: paras,
        onComplete: function(request) {
            new Effect.Appear(document.getElementById(msgDiv));
        },
        onFailure : reportError
        }
    );
}


function goURL(url){
	location.href= url;
}

//trim
function trim(inputString) {
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") {
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") {
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) {
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length);
   }
   return retValue;
}

function tag_check() {
    AjaxTagsCheck('mode=checkTags&tags=' + $('tags').value + '&tmptag=' + $('tmp_tag').value ,'checkTagsMsg');
}


function goToStep1() {
    alert(lang["msgUpMsg4"]);
    location.href="step_1.php";
    return false;
}


function not_email_verificated() {
    alert(lang["user_not_email_verificated_01"]+"\n"+lang["user_not_email_verificated_02"]);
}