//Javascript
var sUserAgent = navigator.userAgent;
var fAppVersion = parseFloat(navigator.appVersion);

function compareVersions(sVersion1, sVersion2) {

    var aVersion1 = sVersion1.split(".");
    var aVersion2 = sVersion2.split(".");

    if (aVersion1.length > aVersion2.length) {
        for (var i=0; i < aVersion1.length - aVersion2.length; i++) {
            aVersion2.push("0");
        }
    } else if (aVersion1.length < aVersion2.length) {
        for (var i=0; i < aVersion2.length - aVersion1.length; i++) {
            aVersion1.push("0");
        }
    }
    for (var i=0; i < aVersion1.length; i++) {

        if (aVersion1[i] < aVersion2[i]) {
            return -1;
        } else if (aVersion1[i] > aVersion2[i]) {
            return 1;
        }
    }
    return 0;

}

var isOpera = sUserAgent.indexOf("Opera") > -1;
var isMinOpera4 = isMinOpera5 = isMinOpera6 = isMinOpera7 = isMinOpera7_5 = false;

if (isOpera) {
    var fOperaVersion;
    if(navigator.appName == "Opera") {
        fOperaVersion = fAppVersion;
    } else {
        var reOperaVersion = new RegExp("Opera (\\d+\\.\\d+)");
        reOperaVersion.test(sUserAgent);
        fOperaVersion = parseFloat(RegExp["$1"]);
    }

    isMinOpera4 = fOperaVersion >= 4;
    isMinOpera5 = fOperaVersion >= 5;
    isMinOpera6 = fOperaVersion >= 6;
    isMinOpera7 = fOperaVersion >= 7;
    isMinOpera7_5 = fOperaVersion >= 7.5;
}

var isKHTML = sUserAgent.indexOf("KHTML") > -1
              || sUserAgent.indexOf("Konqueror") > -1
              || sUserAgent.indexOf("AppleWebKit") > -1;

var isMinSafari1 = isMinSafari1_2 = false;
var isMinKonq2_2 = isMinKonq3 = isMinKonq3_1 = isMinKonq3_2 = false;
var isSafari = false;
if (isKHTML) {
    isSafari = sUserAgent.indexOf("AppleWebKit") > -1;
    isKonq = sUserAgent.indexOf("Konqueror") > -1;

    if (isSafari) {
        var reAppleWebKit = new RegExp("AppleWebKit\\/(\\d+(?:\\.\\d*)?)");
        reAppleWebKit.test(sUserAgent);
        var fAppleWebKitVersion = parseFloat(RegExp["$1"]);
        isMinSafari1 = fAppleWebKitVersion >= 85;
        isMinSafari1_2 = fAppleWebKitVersion >= 124;
        isMinSafari3 = fAppleWebKitVersion >= 510;
    } else if (isKonq) {

        var reKonq = new RegExp("Konqueror\\/(\\d+(?:\\.\\d+(?:\\.\\d)?)?)");
        reKonq.test(sUserAgent);
        isMinKonq2_2 = compareVersions(RegExp["$1"], "2.2") >= 0;
        isMinKonq3 = compareVersions(RegExp["$1"], "3.0") >= 0;
        isMinKonq3_1 = compareVersions(RegExp["$1"], "3.1") >= 0;
        isMinKonq3_2 = compareVersions(RegExp["$1"], "3.2") >= 0;
    }

}

var isIE = sUserAgent.indexOf("compatible") > -1
           && sUserAgent.indexOf("MSIE") > -1
           && !isOpera;

var isMinIE4 = isMinIE5 = isMinIE5_5 = isMinIE6 = isMinIE7 = false;

if (isIE) {
    var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
    reIE.test(sUserAgent);
    var fIEVersion = parseFloat(RegExp["$1"]);

    isMinIE4 = fIEVersion >= 4;
    isMinIE5 = fIEVersion >= 5;
    isMinIE5_5 = fIEVersion >= 5.5;
    isMinIE6 = fIEVersion >= 6.0;
    isMinIE7 = fIEVersion >= 7.0;
}

var isMoz = sUserAgent.indexOf("Gecko") > -1
            && !isKHTML;

var isMinMoz1 = sMinMoz1_4 = isMinMoz1_5 = false;

if (isMoz) {
    var reMoz = new RegExp("rv:(\\d+\\.\\d+(?:\\.\\d+)?)");
    reMoz.test(sUserAgent);
    isMinMoz1 = compareVersions(RegExp["$1"], "1.0") >= 0;
    isMinMoz1_4 = compareVersions(RegExp["$1"], "1.4") >= 0;
    isMinMoz1_5 = compareVersions(RegExp["$1"], "1.5") >= 0;
}

var isNS4 = !isIE && !isOpera && !isMoz && !isKHTML
            && (sUserAgent.indexOf("Mozilla") == 0)
            && (navigator.appName == "Netscape")
            && (fAppVersion >= 4.0 && fAppVersion < 5.0);

var isMinNS4 = isMinNS4_5 = isMinNS4_7 = isMinNS4_8 = false;

if (isNS4) {
    isMinNS4 = true;
    isMinNS4_5 = fAppVersion >= 4.5;
    isMinNS4_7 = fAppVersion >= 4.7;
    isMinNS4_8 = fAppVersion >= 4.8;
}

/* Dreamwraver */
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

/* email check */
function email_check(email) {
	var at="@";
	var dot=".";
	var lat=email.indexOf(at);
	var lstr=email.length;
	var ldot=email.indexOf(dot);
	if (!checkInputValue(email)) return false;
	if (email.indexOf(at)==-1) return false;
	if (email.indexOf(at)==-1 || email.indexOf(at)==0 || email.indexOf(at)==lstr) return false;
	if (email.indexOf(dot)==-1 || email.indexOf(dot)==0 || email.indexOf(dot)==lstr) return false;
	if (email.indexOf(at,(lat+1))!=-1) return false;
	if (email.substring(lat-1,lat)==dot || email.substring(lat+1,lat+2)==dot) return false;
	if (email.indexOf(dot,(lat+2))==-1) return false;
	if (email.indexOf(" ")!=-1) return false;

	return true;
}
function selectAllFormItems(e, form) {
	var ListForm = form;
	if(e.checked==true) {
		for (var i=0; i<ListForm.length; i++)
		{
			if (ListForm.elements[i].checked==false) {
				ListForm.elements[i].checked = true;
			}
		}
	} else {
		for (var i=0; i<ListForm.length; i++)
		{
			if (ListForm.elements[i].checked==true) {
				ListForm.elements[i].checked = false;
			}
		}
	}
}
function checkFormValue(element) {
	if (document.getElementById(element)==undefined || document.getElementById(element)==null)
	{
		alert("項目未選擇或是沒有設定。");
		return false;
	} else {
		var v = document.getElementById(element).value;
		if ( v.replace(/(^\s*)|(\s*$)/gi,"")!='' && v!=0) return true;
			return false;
	}
}

function checkInputValue(value) {
	if ( value.replace(/(^\s*)|(\s*$)/gi,"")!='' && value!=0) return true;
		return false;
}

function shift_this_tab(e) {
	/* fixed with FXCK IE */
	if (e.style.backgroundImage=="" || e.style.backgroundImage=="url(../images/channel-header-out-bg.png)" || e.getAttribute("class")=="tab-out") {
		e.style.backgroundImage="url(../images/channel-header-in-bg.png)";
		e.setAttribute("class", "tab-in");
	} else if (e.style.backgroundImage=="url(../images/channel-header-in-bg.png)" || e.getAttribute("class")=="tab-in") {
		e.style.backgroundImage="url(../images/channel-header-out-bg.png)";
		e.setAttribute("class", "tab-out");
	}
}
function turnon_this_tab(e, id) {
	var parentUL = e.parentNode;
	for(var i=0; i< parentUL.childNodes.length; i++) {
		if(parentUL.childNodes[i].nodeName=="LI" && (parentUL.childNodes[i].style.backgroundImage=="" || parentUL.childNodes[i].style.backgroundImage=="url(../images/channel-header-fixedin-bg.png)" || parentUL.childNodes[i].style.backgroundImage=="" || parentUL.childNodes[i].getAttribute("class")=="tab-fixed-in") )
		{
			parentUL.childNodes[i].setAttribute("class", "tab-out");
			parentUL.childNodes[i].style.backgroundImage = "url(../images/channel-header-out-bg.png)";
		}
	}
	e.setAttribute("class", "tab-fixed-in");
	e.style.backgroundImage = "url(../images/channel-header-fixedin-bg.png)";

	/* call AJAX here to reflash the content with id */
}
function autoCompleteBoxInit(e, types, otherclass) {
	if(checkInputValue(e.value)) {
		xajax_autoCompleteBoxInit(e.value, e.id, types, otherclass);
	}
}
function autoCompleteResponse(result, id, otherclass) {
	var target = (document.getElementById(id)!=undefined) ? document.getElementById(id) : false;
	var result = result.split(",");
	var _html = "<ul>";
	for(var i=0;i<result.length;i++) {
		_html += "<li><div onmouseover=\"this.style.backgroundColor='#bbbbcc';\" onmouseout=\"this.style.backgroundColor='#ffffff';\" onclick=\"autoCompleteFieldResponse('"+result[i]+"','"+id+"');\">"+result[i]+"</div></li>";
	}
	_html += "</ul>";
	if(target) {
		globalajaxboxindex = PM.autoCompleteBox(_html,target, otherclass);
	}
}
function autoCompleteFieldResponse(result, id) {
	var target = (document.getElementById(id)!=undefined) ? document.getElementById(id) : false;
	if(target) target.value = result;
	return false;
}
function loginForm(e) {
	if (checkFormValue('username')==false) { alert('請輸入帳號！'); return false;}
	if (checkFormValue('password')==false) { alert('請輸入密碼！'); return false;}
	e.submit();
}
function closeloginbox() {
	PM._hideMessage(globalajaxboxindex);
}
function userloginbox() {
	var _html = "<div class=\"userloginbox\"><div class=\"ajax-popup-close-button\"><img src=\""+globalpath+"images/ajax_popup_close_button.png\" border=\"0\" width=\"14\" height=\"14\" alt=\"close\" title=\"close\" onclick=\"closeloginbox();\"/></div><h3>會員登入</h3><form method=\"post\" action=\""+globalpath+"login.php\"><input type=\"hidden\" name=\"refurl\" id=\"refurl\" value=\""+referer+"\" /><dfn>帳號：<input type=\"text\" id=\"username\" name=\"username\" value=\"\" size=\"24\" maxlength=\"64\" /></dfn><br /><dfn>密碼：<input type=\"password\" id=\"password\" name=\"password\" value=\"\" size=\"16\" maxlength=\"16\" onkeydown=\"if (event.keyCode == 13) loginForm(this.form);\" />&nbsp;<input type=\"button\" value=\"確認\" onclick=\"loginForm(this.form);\" />&nbsp;<input type=\"reset\" value=\"清除\" /></dfn><br /></form><dfn>忘記密碼？&nbsp;尚未成為會員？</dfn></div>";
	globalajaxboxindex = PM.showMessage(_html, "center", "middle", 0);
}

/* PHP to javascript */
function is_array( mixed_var ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   bugfixed by: Cord
 
    return ( mixed_var instanceof Array );
}
function str_replace(search, replace, subject) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // -    depends on: is_array
    
    var f = search, r = replace, s = subject;
    var ra = is_array(r), sa = is_array(s), f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
 
    while(j = 0, i--){
        while(s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f);
    }
     
    return sa ? s : s[0];
}

/* common prototype */
function makeMaskerInvisibile() {
	/* fixed IE6 div tag cannot cover the select tag */
	if(isMinIE6) {
		var allSelect = document.getElementsByTagName("SELECT");
		for (var i=0;i<allSelect.length; i++) {
			allSelect[i].style.display = (allSelect[i].style.display=="none") ? "inline" : "none";
		}
	}
}
function PageMaster() {
	this._status = null;
	this._messages = new Array();
}
PageMaster.prototype.autoCompleteBox = function(message,dependElement,otherclassname,dashed,timeout) {
	if((typeof(message) != "string")||(message.length == 0)) return -1;
	if(dependElement==undefined) dependElement = document.body;
	otherclassname = (otherclassname==undefined) ? "" : " "+otherclassname;
	if(dashed==undefined) dashed=22;
	if(timeout==undefined) timeout=5000;
	makeMaskerInvisibile();
	var oMessage = document.createElement("div");
	var fx = new Fx.Tween(oMessage, {duration:1500,wait:false,transition:Fx.Transitions.Quad.easeOut});
	oMessage.innerHTML = message;
	oMessage.style.position="absolute";
	oMessage.className = "search-auto-complete-box"+otherclassname;
	oMessage.style.top = dependElement.offsetTop + dashed + "px";
	oMessage.style.left = dependElement.offsetLeft + "px";
	document.body.appendChild(oMessage);
	var index=this._messages.push(oMessage)-1;
	fx.start('opacity','0','1');
	if (timeout>0) window.setTimeout("PM._hideMessage("+index+")",timeout);
	return index;	
}
PageMaster.prototype.showMessage = function(message,align,valign,timeout) {
	if((typeof(message) != "string")||(message.length == 0)) return -1;
	if(align==undefined) align = "center";
	if(valign==undefined) valign="middle";
	if(timeout==undefined) timeout=2000;
	if(isIE && isMinIE6) makeMaskerInvisibile();
	var ScrollLeft = document.documentElement.scrollLeft;
	var ScrollTop = document.documentElement.scrollTop;
	var oMessage = document.createElement("div");
	var fx = new Fx.Tween(oMessage, {duration:1500,wait:false,transition:Fx.Transitions.Quad.easeOut});
	oMessage.innerHTML = message;
	oMessage.style.position="absolute";
	oMessage.className = "ajaxMessage ajaxSuccessMessage";
	oMessage.style.margin = "0px";
	oMessage._align = align;
	oMessage._valign = valign;
	document.body.appendChild(oMessage);
	var index=this._messages.push(oMessage)-1;
	fx.start('opacity','0','1');
	this.updateMessages();
	if (timeout>0) window.setTimeout("PM._hideMessage("+index+")",timeout);
	return index;
};
PageMaster.prototype.showSuccessMessage = function(message,align,valign,timeout) {
	if((typeof(message) != "string")||(message.length == 0)) return -1;
	if(align==undefined) align = "center";
	if(valign==undefined) valign="middle";
	if(timeout==undefined) timeout=2000;
	if(isIE && isMinIE6) makeMaskerInvisibile();
	var ScrollLeft = document.documentElement.scrollLeft;
	var ScrollTop = document.documentElement.scrollTop;
	var oMessage = document.createElement("div");
	var fx = new Fx.Tween(oMessage, {duration:1500,wait:false,transition:Fx.Transitions.Quad.easeOut});
	oMessage.innerHTML = "<div align=\"center\"><img src=\""+globalpath+"images/icons/agt_action_success_ok.png\" border=\"0\" width=\"48\" height=\"48\" /></div><br class=\"clear\">"+message;
	oMessage.style.position="absolute";
	oMessage.className = "ajaxMessage ajaxSuccessMessage";
	oMessage.style.margin = "0px";
	oMessage._align = align;
	oMessage._valign = valign;
	document.body.appendChild(oMessage);
	var index=this._messages.push(oMessage)-1;
	fx.start('opacity','0','1');
	this.updateMessages();
	if (timeout>0) window.setTimeout("PM._hideMessage("+index+")",timeout);
	return index;
};
PageMaster.prototype.showErrorMessage = function(message,align,valign,timeout) {
	if((typeof(message) != "string")||(message.length == 0)) return-1;
	if(align==undefined) align = "center";
	if(valign==undefined) valign="middle";
	if(timeout==undefined) timeout=2000;
	if(isIE && isMinIE6) makeMaskerInvisibile();
	var oMessage = document.createElement("div");
	var fx = new Fx.Tween(oMessage, {duration:1500,wait:false,transition:Fx.Transitions.Quad.easeOut});
	oMessage.innerHTML = "<div align=\"center\"><img src=\""+globalpath+"images/icons/agt_action_fail_error.png\" border=\"0\" width=\"48\" height=\"48\" /></div><br class=\"clear\">"+message;
	oMessage.style.position="absolute";
	oMessage.className = "ajaxMessage ajaxErrorMessage";
	oMessage.style.margin = "0px";
	oMessage._align = align;
	oMessage._valign = valign;
	document.body.appendChild(oMessage);
	var index=this._messages.push(oMessage)-1;
	fx.start('opacity','0','1');
	this.updateMessages();
	if (timeout>0) window.setTimeout("PM._hideMessage("+index+")",timeout);
	return index;
};
PageMaster.prototype._hideMessage = function(index) {
	if(isIE && isMinIE6) makeMaskerInvisibile();
	document.body.removeChild(this._messages[index]);
	this._messages.splice(index,1,null);
	while((this._messages.length>0) && (this._messages[this._messages.length-1] == null))
		this._messages.pop();
};
PageMaster.prototype.updateMessages = function() {
	for(var i=0;i<this._messages.length;i++) {
		if(this._messages[i]==null) continue;
		var ScrollLeft = document.documentElement.scrollLeft;
		var ScrollTop = document.documentElement.scrollTop;
		switch(this._messages[i]._align) {
			case"left":
				this._messages[i].style.left = ScrollLeft+"px";
				break;
			case"center":
				this._messages[i].style.left = (ScrollLeft+(document.documentElement.clientWidth-this._messages[i].offsetWidth)/2)+"px";
				break;
			case"right":
				this._messages[i].style.left = (ScrollLeft+document.documentElement.clientWidth-this._messages[i].offsetWidth)+"px";
				break;
		};
		
		switch(this._messages[i]._valign) {
			case"top":
				this._messages[i].style.top = ScrollTop+"px";
				break;
			case"middle":
				this._messages[i].style.top = (ScrollTop+(document.documentElement.clientHeight-this._messages[i].offsetHeight)/2)+"px";
				break;
			case"bottom":
				this._messages[i].style.top = (ScrollTop+document.documentElement.clientHeight-this._messages[i].offsetHeight)+"px";
				break;
		};
	};
};

var PM=new PageMaster();

//////////////////////////////////// xml2array() ////////////////////////////////////////
//See http://www.openjs.com/scripts/xml_parser/
var not_whitespace = new RegExp(/[^\s]/);//This can be given inside the funciton - I made it a global variable to make the scipt a little bit faster.
var parent_count;
//Process the xml data
function xml2array(xmlDoc,parent_count) {
	var arr;
	var parent = "";
	parent_count = parent_count || new Object;

	var attribute_inside = 0; /*:CONFIG: Value - 1 or 0
	*	If 1, Value and Attribute will be shown inside the tag - like this...
	*	For the XML string...
	*	<guid isPermaLink="true">http://www.bin-co.com/</guid>
	*	The resulting array will be...
	*	array['guid']['value'] = "http://www.bin-co.com/";
	*	array['guid']['attribute_isPermaLink'] = "true";
	*	
	*	If 0, the value will be inside the tag but the attribute will be outside - like this...	
	*	For the same XML String the resulting array will be...
	*	array['guid'] = "http://www.bin-co.com/";
	*	array['attribute_guid_isPermaLink'] = "true";
	*/

	if(xmlDoc.nodeName && xmlDoc.nodeName.charAt(0) != "#") {
		if(xmlDoc.childNodes.length > 1) { //If its a parent
			arr = new Object;
			parent = xmlDoc.nodeName;
			
		}
	}
	var value = xmlDoc.nodeValue;
	if(xmlDoc.parentNode && xmlDoc.parentNode.nodeName && value) {
		if(not_whitespace.test(value)) {//If its a child
			arr = new Object;
			arr[xmlDoc.parentNode.nodeName] = value;
		}
	}

	if(xmlDoc.childNodes.length) {
		if(xmlDoc.childNodes.length == 1) { //Just one item in this tag.
			arr = xml2array(xmlDoc.childNodes[0],parent_count); //:RECURSION:
		} else { //If there is more than one childNodes, go thru them one by one and get their results.
			var index = 0;

			for(var i=0; i<xmlDoc.childNodes.length; i++) {//Go thru all the child nodes.
				var temp = xml2array(xmlDoc.childNodes[i],parent_count); //:RECURSION:
				if(temp) {
					var assoc = false;
					var arr_count = 0;
					for(key in temp) {
						if(isNaN(key)) assoc = true;
						arr_count++;
						if(arr_count>2) break;//We just need to know wether it is a single value array or not
					}

					if(assoc && arr_count == 1) {
						if(arr[key]) { 	//If another element exists with the same tag name before,
										//		put it in a numeric array.
							//Find out how many time this parent made its appearance
							if(!parent_count || !parent_count[key]) {
								parent_count[key] = 0;

								var temp_arr = arr[key];
								arr[key] = new Object;
								arr[key][0] = temp_arr;
							}
							parent_count[key]++;
							arr[key][parent_count[key]] = temp[key]; //Members of of a numeric array
						} else {
							parent_count[key] = 0;
							arr[key] = temp[key];
							if(xmlDoc.childNodes[i].attributes.length) {
								for(var j=0; j<xmlDoc.childNodes[i].attributes.length; j++) {
									var nname = xmlDoc.childNodes[i].attributes[j].nodeName;
									if(nname) {
										/* Value and Attribute inside the tag */
										if(attribute_inside) {
											var temp_arr = arr[key];
											arr[key] = new Object;
											arr[key]['value'] = temp_arr;
											arr[key]['attribute_'+nname] = xmlDoc.childNodes[i].attributes[j].nodeValue;
										} else {
										/* Value in the tag and Attribute otside the tag(in parent) */
											arr['attribute_' + key + '_' + nname] = xmlDoc.childNodes[i].attributes[j].nodeValue;
										}
									}
								} //End of 'for(var j=0; j<xmlDoc. ...'
							} //End of 'if(xmlDoc.childNodes[i] ...'
						}
					} else {
						arr[index] = temp;
						index++;
					}
				} //End of 'if(temp) {'
			} //End of 'for(var i=0; i<xmlDoc. ...'
		}
	}

	if(parent && arr) {
		var temp = arr;
		arr = new Object;
		
		arr[parent] = temp;
	}
	return arr;
}