// JavaScript Document

/*
 * Joe
 * 
 * 
 * 
*/

var EVENT_PHOTO_DIR = "../img/photos/";
var IMG_DIR ="../img/";
var XML_SERVER = "./admin.server.php";
var SERVER_ERROR_404 = " XML文件丢失。";

var messageStr = "Yes";


function httpRequest()
{
	var xmlhttp;
	// code for Mozilla, etc.
	if (window.XMLHttpRequest)
	{
		xmlhttp = new XMLHttpRequest();
		if (xmlhttp.overrideMimeType) 
		{
			xmlhttp.overrideMimeType('text/xml');
		}
	}// code for ie 6
	else if (window.ActiveXObject)
	{
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {
			//
		}
	}
	return xmlhttp;
}


function getUrl( url, cb, data ) 
{
	var xmlhttp = httpRequest();//getXMLDoc();
	
	xmlhttp.open("GET", url);
	xmlhttp.onreadystatechange = function()
	{
		if ( xmlhttp.readyState == 4 )
		{
			//alert( xmlhttp.responseText );
			cb(xmlhttp.status, xmlhttp.getAllResponseHeaders(), xmlhttp.responseXML ,url);	
		}
	};

	xmlhttp.send(data);
}


function sendRequest( url , cb , data )
{
	
	//alert( data );
	
	var timestamp = new Date().getTime();
	url = url + "?timeStamp=" + timestamp;
	var xmlhttp = httpRequest();//getXMLDoc();
	
	xmlhttp.onreadystatechange = function () 
	{
		if (xmlhttp.readyState == 4)
		{
			cb( xmlhttp );
		}
	};


	xmlhttp.open("POST", url, true );
	xmlhttp.setRequestHeader( "Content-Type" , "application/x-www-form-urlencoded; charset=UTF-8" );
	//xmlhttp.setRequestHeader( "Content-Type" , "charset=UTF-8" );
	xmlhttp.send(data);
	return timestamp;
}



/*
   name - name of the cookie
   [path] - path of the cookie (must be same as path used to create cookie)
   [domain] - domain of the cookie (must be same as domain used to
     create cookie)
   path and domain default if assigned null or omitted if no explicit
     argument proceeds
*/

function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}



function GetCookie (name){
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
            return getCookieVal (j);

        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return null;
}


function getCookieVal (offset){
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1)
        endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}


function SetCookie (name, value ){
    var argv = SetCookie.arguments;
    var argc = SetCookie.arguments.length;
   
    var expires = (argc > 2) ? argv[2] : null;
    var path = (argc > 3) ? argv[3] : null;
    var domain = (argc > 4) ? argv[4] : null;
    var secure = (argc > 5) ? argv[5] : false;
   
    document.cookie = name + "=" + escape (value) +
     ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
     ((path == null) ? "" : ("; path=" + path)) +
     ((domain == null) ? "" : ("; domain=" + domain)) +
     ((secure == true) ? "; secure" : "");
}


//trim()

String.prototype.trim = function()
{
    return this.replace(/(^[\s]*)|([\s]*$)/g, "");
};

String.prototype.toDate = function( )
{
	var str = this.toString();
    var datetime = new DateTime(  str.substr(0,4), str.substr(5,2),  str.substr(8,2) , str.substr(8,2) );
    return datetime; 
};

function DateTime(year, month,  date , time )
{
	this.year= year;
	this.month= month;
	this.date= date;
	this.time= time;
}

function $( str )
{
	
	return document.getElementById( str );
		
}



//0/100
function setOpacity( obj,value ){
	
	//alert( value );
	
	value  = parseInt( value );
	try{
			
		if( document.all ){
			obj.style.filter = "alpha(opacity="+value+")";
			//obj.filters.alpha.opacity = value;
		}
		else{
			value = value * 0.01;
			obj.style.opacity = value;
		}	
	}
	catch( e ){}
	
}


function getLeft( obj ) 
{
	var x = 0;
	// Return the x coordinate of an element relative to the page.	
	while (obj.offsetParent)
	{
		x += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	
	return x;
}

function getTop( obj ) 
{
	// Return the y coordinate of an element relative to the page.
	var y =  0;
	
	while (obj.offsetParent)
	{
		//document.getElementById( "t" ).innerHTML += obj.offsetTop+"-";
		y += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return y;
}

function getXY( obj )
{
	// Return the y coordinate of an element relative to the page.
	var y = 0;
	var x = 0;
	
	while (obj.offsetParent)
	{
		//document.getElementById( "t" ).innerHTML += obj.offsetTop+"-";
		y += obj.offsetTop;
		obj = obj.offsetParent;
		
		x += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	return new Point( x, y );
}

function Point( x,y )
{
	this.x = x|| 0;
	this.y = y|| 0;
	
}


function transform( inprogress , complete , intv,  sce )
{
	if( typeof inprogress != "function" ) 
	{
		alert( "inprogress needs to be function( count )" );
		return null;
	}
	
	if( typeof complete != "function" ) 
	{
		alert( "complete needs to be function" );
		return null;
	}
	
	var _this = this;
	var timerID = 0;
	//0 - 100;
	var count = 0;
	
	this.intv = intv || 20;
	if( this.intv <=0 || this.intv >=100 ) this.intv = 20;
	
	this.sce = sce || 100;
	if( this.sce <= 0  ) this.sce = 100;
	
	var runner = function()
	{
		
		if( count > 100 )
		{
			window.clearTimeout( timerID );
			complete();
		}
		else
		{
			inprogress( count );
			count = count + _this.intv;
			
			//_this.intv = _this.intv * 0.9;
			//先快后慢
			//if( _this.intv < 2  ) _this.intv = 2;
			
			timerID = window.setTimeout( runner , _this.sce );
		}	
		
	};
	
	this.run = function()
	{
		runner();
	};
	
	this.stop = function()
	{
		window.clearTimeout( timerID );
	}
	
	
}


var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();



//class msgQueue
function MsgQueue()
{
	var _this = this;
	var msgs = new Array();
	var msgid = 0;
	var theMsgTop = 0;
	var lastHeight = 0;
	
	this.shownext = function()
	{
		document.body.removeChild( msgs[0].thebody )
		msgs.remove( msgs[0] );
		
		if( msgs.length > 0 ) 
		{
			msgs[0].run();
		}
	};
	
	this.getNextID = function()
	{
		msgid ++;
		return msgid
	};
		
	this.pushMsg = function( html, type )
	{
		
		if( msgs.length > 0 && ( document.body.scrollTop + document.documentElement.clientHeight ) > theMsgTop + lastHeight + 30   ) 
		{
			lastHeight = msgs[ msgs.length -1 ].thebody.offsetHeight;
			theMsgTop = theMsgTop + lastHeight + 12;
		}
		else
		{
			//theMsgTop = pageYOffset + 10;
			theMsgTop = document.body.scrollTop + 10 ;
		}
		
		msgs[msgs.length] = new MsgFly( _this, html , type, _this.getNextID(), theMsgTop  );
		if( msgs.length == 1 ) msgs[0].run();	
	};

}

 
//class msgfly
function MsgFly( parent,  html, type ,id, top )
{
	
	var _this = this;
	var MSG_TYPE_ERROR = "error";
	var MSG_TYPE_MSG = "msg";
	var TIME_INTV = 100;

	var max = 60; 
	var count = 140;
	var theTop = top;
	
	this.id = id;
	this.thebody = document.createElement("div")
	document.body.appendChild( this.thebody  );
	this.thebody.style.display = "none";
	this.thebody.style.width = "200px";
	this.thebody.style.left = 10 +"px";

	this.thebody.style.position = "absolute";
	this.thebody.style.top  = ( theTop )+"px";
	
	this.thebody.style.paddingLeft = this.thebody.style.paddingRight =  "10px";
	this.thebody.style.paddingTop = this.thebody.style.paddingBottom =  "5px";
	this.thebody.style.display = "";
	
	if( document.all )
	{
		//this.thebody.style.background = "#eeeeee";
		//this.thebody.style.wordWrap = "break-word";
		//this.thebody.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=1)";
	}
	//this.thebody.style.backgroundImage = "url(../img/trans.gif)";
	
	var imgButton = document.createElement("img");
	this.thebody.appendChild( imgButton );
	imgButton.src= "../img/close_black.png";
	
	imgButton.style.cursor = "pointer";
	imgButton.border = 0;
	imgButton.style.position = "relative";
	
	imgButton.style.left = "-13px";
	imgButton.style.top = "-8px";
	

	imgButton.style.zIndex = 2;
	
	var msgdiv = this.thebody.appendChild( document.createElement("div") )
	msgdiv.innerHTML = html;
	
	msgdiv.style.position = "relative";
	msgdiv.style.left = "2px";
	msgdiv.style.top = "-20px";
	

	imgButton.onclick = function( event )
	{
		//window.clearInterval( intervalID );
		//parent.shownext();
		_this.thebody.style.display ="none";
		//delete _this;
	};


	var intervalID = "0";
	
	if( type == MSG_TYPE_ERROR ) 
	{
		msgdiv.className = "error";
	}
	else
	{
		msgdiv.className = "msg";
	}
	
	msgdiv.style.padding = "10px";
	
	this.flyout = function()
	{
		if( count <= max )
		{
			setOpacity( _this.thebody , count / max * 90 );
				
			if( count <= 0 || _this.thebody.style.display == "none" ) 
			{			
				window.clearInterval( intervalID );
				parent.shownext();
				delete _this;
			}
		}
		
		count = count - 10;
	};	
	
	this.run = function()
	{
		//_this.thebody.style.top = ( window.pageYOffset + 10 )+"px";
		_this.thebody.style.top = theTop+"px";
		//_this.thebody.style.left = document.documentElement.clientWidth - this.thebody.offsetWidth - 10 +"px";
		_this.thebody.style.left = 10 +"px";
		
		//alert( theTop );
		//_this.setDisplay( true );
		intervalID = setInterval( _this.flyout , TIME_INTV );
	};
	
	this.setDisplay = function( bool )
	{
		if( bool )
		{
			//this.thebody.style.left = document.documentElement.clientWidth - this.thebody.offsetWidth - 10 +"px";
			this.thebody.style.display = "";
		}
		else
		{
			this.thebody.style.display = "none";	
		}
	};
}
 
var MSG_OUTPUT = new MsgQueue();




function AddEventListener(obj, eventString, eventmethod )
{
	if( document.all )
	{
		obj.attachEvent( "on"+eventString, eventmethod );	
	}
	else
	{
		obj.addEventListener( eventString, eventmethod,false );
	}

}


function RemoveEventListener(obj, eventString, eventmethod )
{
	if( document.all )
	{
		obj.detachEvent( "on"+eventString, eventmethod );	
	}
	else
	{
		obj.removeEventListener( eventString, eventmethod , false );
	}
} 




Number.prototype.toCurrency = function()
{
	var num = this.toString();
	var tempNum = "";
	var end = "00";
		
	//check for decimal number
	if ( num.indexOf('.') != -1)
	{  //number ends with a decimal point
		if (num.indexOf('.') == this.length-1)
	    {
	    	num += "00";
	    }
	    if ( num.indexOf('.') == this.length-2)
	    { //number ends with a single digit
	   		num += "0";
	    }
		
	    var a = num.split(".");
	   	num = new String( a[0] );   //the part we will commify
	    end = a[1] //the decimal place we will ignore and add back later
	    
	}
	
	if( num.length > 3 )
	{
		var i;
		for( i = num.length - 3 ; i >= 0 ;i = i - 3 )    
		{
			tempNum  = "," + num.substr( i , 3  ) + tempNum; 
		}
		tempNum = num.substr(0, 3+i)  +tempNum;
	}
	else
	{
		tempNum = num;	
	}
		
	return "￥ " + tempNum +"."+end.substr(0,2);
};



Number.prototype.format = function( len )
{
	var num = this.toString();
	
	for( var i=0;i< (len - num.length);i++ )
	{
		num = "0"+num;
	}
	return num;
};



function getNodeData( childNodes )
{
	var value = "";	
	if( childNodes )
	{
		for(var j=0;j<childNodes.length;j++ )
		{
			value += childNodes[j].data;
		}
	}
	return value;
}




function getXmlText( xml, string )
{
	var text = "";
	
	try
	{
		text = getNodeData( xml.getElementsByTagName( string ).item(0).childNodes );	
	}
	catch(e){
		
	}
	
	return text; 
}


function isRegisterUserName(s) 
{ 
	var patrn=/^[a-zA-Z]{1}([a-zA-Z0-9]|[-._]){4,49}$/;
	
	if (patrn.exec(s)) 
	{
		return true;
	}
	return false; 
}



//class
function serverMsg( xml, debug )
{
	var _this = this;
	
	if( debug ) alert(  xml.responseText );
	this.error = "";
	this.status = "";
	this.data = "";
	this.timestamp = "";
	this.items = new Array();
	

	try
	{
		var node = xml.responseXML.documentElement;

		if( node.getElementsByTagName('status').item(0) )
		{
			if( node.getElementsByTagName('status').item(0) )
			{
				this.status = node.getElementsByTagName('status').item(0).childNodes[0].data;
				this.isOk = ( this.status == "ok" );
			}
			else
			{
				this.status = "error";
				//this.error = "The status is unknow.";
			}
			
			if( node.getElementsByTagName('data').item(0) )
			{
				this.data = node.getElementsByTagName('data').item(0);
				this.items = this.data.getElementsByTagName('item');
	
			}
			
			if( node.getElementsByTagName('error').item(0) )
			{
				this.error = node.getElementsByTagName('error').item(0);
			}
			

			if( node.getElementsByTagName('timestamp').item(0).childNodes[0]  )
			{
				this.timestamp = node.getElementsByTagName('timestamp').item(0).childNodes[0].data;
			}
		}
	}
	catch( e )
	{
		this.status = "error";	
		this.error = "The server does not return valid XML file.";
		alert( e );
	}
	
	
}


//调用一个远程服务器的函数
function RPC( SERVER_XML, functionName, debug , callBackMethod )
{
	if( arguments.length >= 4 )
	{
		var data = "&com="+functionName;
		for(var i=4; i< arguments.length ;i++)
		{
			data += "&arg[]="+ encodeURIComponent( arguments[i] );
		}
		
		var timestamp = sendRequest( SERVER_XML , 
		function( xmlhttp )
		{
				if( xmlhttp.status == 200 )
				{
					
					var msg = new serverMsg( xmlhttp, debug );

					if( timestamp == msg.timestamp ) 
					{						
						callBackMethod( msg, xmlhttp );
					}
				}
				else if( xmlhttp.status == 404 )
				{
					if( MSG_OUTPUT ) MSG_OUTPUT.pushMsg( SERVER_ERROR_404 , "error" );
				}
		}
		, data );
		
	}
	return false;
}

	var months = new Array("January",  "February", "March" , "April" , "May", "June" , "July" , "Aguest", "September" , "October" , "November", "December");




function resizeImg(  img, width, height )
{
	var imgWidth = img.offsetWidth;
	var imgHeight = img.offsetHeight;
		
			if( imgWidth > width )
			{
				img.style.width = width + "px";
				 img.style.height =  parseInt( width * imgHeight / imgWidth ) + "px";
			}		
			else if( imgHeight > height )
			{
				 img.style.height = height + "px";
				 img.style.width = parseInt( height * imgWidth / imgHeight ) + "px";
			}
}



function File( path )
{
	this.filename = path.substring( path.lastIndexOf( "/" )+1, path.lastIndexOf( "." ) );
	this.path = path.substr( 0, path.lastIndexOf( "/" )+1 );
	this.ext = path.substr( path.lastIndexOf( "." ), path.length );
	this.fullpath = path;
}



//ie6 tested
function tableLayout(parent,parentNode )
{
	var _this = this;
	
	this.parent = parent;
	//if( typeof parent == "string" ) this.parent = document.getElementById( parent );
	//this.thebody = document.createElement("div");
	this.parentNode = parentNode;
	if( typeof this.parentNode == "string" ) this.parentNode = document.getElementById( this.parentNode );
	
	this.table = this.parentNode.appendChild( document.createElement("table") );
	this.table.border = 0;
	this.table.cellPadding = this.table.cellSpacing = 0;
	this.table.width = "100%";
	
	this.tbody = this.table.appendChild(  document.createElement("tbody")  );

	var temprow = this.tbody.appendChild( document.createElement("tr") ); 

	this.cells = new Array();
	
	this.addCell = function( html )
	{
		var cell = temprow.appendChild( document.createElement("td") );
		_this.cells[_this.cells.length] = cell;
		
		if( typeof html == "string" )
		{
			cell.innerHTML = html || "";
		}
		else if( typeof html == "object" )
		{
			cell.appendChild( html );
		}
		
		return cell;
	};
	
	this.addSeparateRow = function()
	{
		temprow = _this.tbody.appendChild( document.createElement("tr") );
		return temprow;
	};
	
	this.addRow = function()
	{
		return this.addSeparateRow();
	};
	
	
	this.clear = function()
	{
		this.table.removeChild( this.tbody );
		this.tbody = this.table.appendChild( document.createElement("tbody") );
		temprow = this.tbody.appendChild( document.createElement("tr") );
	}
	
}

function twoDigs( num )
{
	num = num+"";
	if( num.length <=1 ) num = "0"+num;
	if( num.length >2 ) num = num.substring( 0,2 );
	return num;
}

function tohex( num )
{
	return Number( num ).toString(16); 
}

function todec( num )
{
	return  parseInt( num ,16 );
}


function contactOnSubmit( obj )
{
	
	var name = document.getElementById( "name" );
	var mail = document.getElementById( "email" );
	var phone = document.getElementById( "phone" );
	
	
//	var subject = document.getElementById( "subject" );
//	var message = document.getElementById( "message" );
	
	if( name.value == "" )
	{
		alert("Please enter your name.");
		return false;
	}
	else if(  mail.value =="" )
	{
		alert("Please enter your e-mail address.");
		return false;
	}
	else if(  phone.value =="" )
	{
		alert("Please enter your phone number.");
		return false;
	}
	
	
	return true;
	
	
}


function echeck( email ) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   //var address = document.forms[form_id].elements[email].value;
   
   if(reg.test(email) == false) {
      //alert('Invalid Email Address');
      return false;
   }
   
   return true;
}


function getRandomNum( Min, Max ){
        var Range = Max - Min;
        var Rand = Math.random();
        return(Min + Math.round(Rand * Range));
}







String.prototype.isEmail = function( )
{
	var str = this.toString();
	if (str.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
	return true;
	else
	return false;

};



function bookmarksite(title, url){
if (document.all)
window.external.AddFavorite(url, title);
else if (window.sidebar)
window.sidebar.addPanel(title, url, "")
}

