﻿var userAgent = navigator.userAgent.toLowerCase();
var is_opera  = ((userAgent.indexOf('opera') != -1) || (typeof(window.opera) != 'undefined'));
var is_saf    = ((userAgent.indexOf('applewebkit') != -1) || (navigator.vendor == 'Apple Computer, Inc.'));
var is_webtv  = (userAgent.indexOf('webtv') != -1);
var is_ie     = ((userAgent.indexOf('msie') != -1) && (!is_opera) && (!is_saf) && (!is_webtv));
var is_ie4    = ((is_ie) && (userAgent.indexOf('msie 4.') != -1));
var is_moz    = ((navigator.product == 'Gecko') && (!is_saf));
var is_kon    = (userAgent.indexOf('konqueror') != -1);
var is_ns     = ((userAgent.indexOf('compatible') == -1) && (userAgent.indexOf('mozilla') != -1) && (!is_opera) && (!is_webtv) && (!is_saf));
var is_ns4    = ((is_ns) && (parseInt(navigator.appVersion) == 4));
var is_mac    = (userAgent.indexOf('mac') != -1);

var siteurl = 'http://localhost/choxe';

function fetch_object(idname)
{
	if (document.getElementById)
	{
		return document.getElementById(idname);
	}
	else if (document.all)
	{
		return document.all[idname];
	}
	else if (document.layers)
	{
		return document.layers[idname];
	}
	else
	{
		return null;
	}
}

function fetch_tags(tag)
{
	if (typeof document.getElementsByTagName != 'undefined')
	{
		return document.getElementsByTagName(tag);
	}
	else if (document.all && document.all.tags)
	{
		return document.all.tags(tag);
	}
	else
	{
		return new Array();
	}
}

function createxmlHttp() {
		var xmlHttp;
		try	{
			xmlHttp = new XMLHttpRequest();
		}
		catch(e) {
				var XmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0',
												'MSXML2.XMLHTTP.5.0',
												'MSXML2.XMLHTTP.4.0',
												'MSXML2.XMLHTTP.3.0',
												'MSXML2.XMLHTTP',
												'Microsoft.XMLHTTP');
				for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++){
					try	{
							xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
					}
					catch (e) {}
				}
		}
		if (!xmlHttp)
			alert('Sorry we can not creat an ActiveX on your browser, please update your browser version or change to another browser.');
		else
		return xmlHttp;
}

function check_uncheck(fid){
	var f= document.frm;
	if(f.checkall.checked){
		CheckAllCheckbox(f,fid);
	}else{
		UnCheckAllCheckbox(f,fid);
	}			
}

function CheckAllCheckbox(f,checkboxname){
	var len=f.elements.length;
	for(var i=0;i<len;i++){
		if(f.elements[i].name==checkboxname){
			f.elements[i].checked=true;
		}
	}
	return;
}

//-------------------------------------------------------------------------------------------
function UnCheckAllCheckbox(f,checkboxname){
	var len=f.elements.length;
	for(var i=0;i<len;i++){
		if(f.elements[i].name==checkboxname){
			f.elements[i].checked=false;
		}
	}
	return;
}

//------------------------------------------------
function LTrim(Str) {
	return Str.replace(/^\s+/, '');
}

//------------------------------------------------
function RTrim(Str) {
	return Str.replace(/\s+$/, '');
}
//------------------------------------------------
function Trim(Str) {
	return RTrim(LTrim(Str));
}
//-------------------------------------------------------------------------------------------
function isEmpty(Str) {
	empty = (Str === "") ? true :  false;
	return empty;
}

//-------------------------------------------------------------------------------
function isNumber(Digit) {
	return /^\d+[\.\d*]?$/.test(Digit);
}

//------------------------------------------------------------------------------
function isAlphabet(Digit) {
	return /^[a-zA-Z]$/.test(Digit);
}

//-------------------------------------------------------------------------------
function isInteger(Str) {
	return /^[+-]?\d+$/.test(Str);
}

//-------------------------------------------------------------------------------
function isFloat(Str) {
		return /^[+-]?\d+\.{1}\d*$/.test(Str);
}

//-------------------------------------------------------------------------------
function isCurrency(Str) {
		return /^\d+[.]{1}[0-9]{2,}$/.test(Str);
}

function isDomain (Str) {
	// The pattern for matching all special characters. 
  	//These characters include ( ) < > [ ] " | \ / ~ ! @ # $ % ^ & ? ` ' : ; , 
	var specialChars="\\(\\)<>#\\$&\\*!`\\^\\?~|/@,;:\\\\\\\"\\.\\[\\]";
	// The range of characters allowed in a username or domainname. 
	// It really states which chars aren't allowed. 
	var validChars="\[^\\s" + specialChars + "\]";
	 // An atom (basically a series of  non-special characters.) 
	var atom=validChars + '+';
	// The structure of a normal domain 
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	
	// Check if IP
	var ipDomainPat=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
	var IPArray=Str.match(ipDomainPat);
	if (IPArray!=null) {
  	// this is an IP address
	 	 for (var i=1;i<=4;i++) {
	    		if (IPArray[i]>255) {
	 			return false
	   		 }
   		 }
	}
	// Check Domain
	var domainArray=Str.match(domainPat)
	if (domainArray==null) {
    		return false;
	}

	/* domain name seems valid, but now make sure that it ends in a
	 three-letter word (like com, edu, gov ... ) or a two-letter word,
   	representing country (uk, vn) or a four-letter word (.info), and that there's a hostname preceding 
   	the domain or country. */

	/* Now we need to break up the domain to get a count of how many atoms
	it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=Str.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>4) {
	 // the address must end in a two letter or three letter word or four-letter word.
		return false;
	}

	// Make sure there's a host name preceding the domain.
	if (len<2) {
   		 return false;
	}

	return true;
}

function isPhone(strPhone) {
	return  /^(\d{6,15})$/.test(strPhone);
	//return  /^[\+\-\(]?(\d*[\.\-\(\)\s\+]*\d*)*$/.test(strPhone);
}

function isMobile(strMobile) {
	return  /^(\d{9,15})$/.test(strMobile);
	//return  /^[\+\-\(]?(\d*[\.\-\(\)\s\+]*\d*)*$/.test(strPhone);
}

function isUser (Str) {
	var specialChars="\\(\\)<>#\\$&\\*!`\\^\\?~|/@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	/* The pattern applies if the "user" is a quoted string (in
   	which case, there are no rules about which characters are allowed
   	and which aren't; anything goes).  E.g. "le nguyen vu"@webtome.com
   	is a valid (legal) e-mail address. */
	var quotedUser="(\"[^\"]*\")";
	var atom=validChars + '+'
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	// See if "user" is valid 
	if (Str.match(userPat)==null) {
    		return false ;
	}
	return true;
}

function isEmail (emailStr) {
	/* The pattern for matching fits the user@domain format. */
	var emailPat=/^(.+)@(.+)$/ ;
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {
 	 /* Too many/few @'s or something; basically, this address doesn't
    	 even fit the general mould of a valid e-mail address. */
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];

	// See if "user" is valid 
	if (!isUser(user)) {
    	// user is not valid
   		 return false ;
	}

	// Check Domain
	if (!isDomain(domain)) {
   		return false;
	}
	return true;
}

function openNewWindow(linkurl,imgh,imgw,s) {
	var w = screen.availWidth;
	var h = screen.availHeight;
	var leftPos = (w-imgw)/2, topPos = (h-imgh)/2;
	window.open(linkurl,'popup','location=0,status=0,scrollbars='+s+',width=' + imgw + ',height=' + imgh + ',top=' + topPos + ',left=' + leftPos);
}

function getExtension(fileName){
		return fileName.substr(fileName.lastIndexOf(".")+1);
}

function hiddeContentBlock(blid) {
	if(fetch_object('block_content_'+blid).style.display == 'none') {
		fetch_object('block_content_'+blid).style.display ='block';
	} else {
		fetch_object('block_content_'+blid).style.display ='none';
	}				
}	

function showAlert(e_name,msg){
	var eObj = document.getElementById(e_name + '_err');
	if(eObj){
		if(msg!=null){	
			eObj.innerHTML = msg + "<br>";
		}
		eObj.style.display = '';	
	}
}
function hideAlert(e_name){
	var eObj = document.getElementById(e_name + '_err');
	if(eObj){
		eObj.style.display = 'none';	
	}
}

function FormatNumber(str){
			var strTemp = GetNumber(str);
			if(strTemp.length <= 3)
				return strTemp;
			strResult = "";
			for(var i =0; i< strTemp.length; i++)
				strTemp = strTemp.replace(",", "");
			for(var i = strTemp.length; i>=0; i--)
			{
				if(strResult.length >0 && (strTemp.length - i -1) % 3 == 0)
					strResult = "," + strResult;
				strResult = strTemp.substring(i, i + 1) + strResult;
			}	
			return strResult;
		}
		
function GetNumber(str,ale)
			{
				for(var i = 0; i < str.length; i++)
				{	
					var temp = str.substring(i, i + 1);		
					if(!(temp >= 0 && temp <=9))
					{
						alert(ale);
						return str.substring(0, i);
					}
					
				}
				return str;
			}

function aj_fetch_string(str) {
	str = str.replace(/&/g,"**am**");
	str = str.replace(/=/g,"**eq**");
	str = str.replace(/\+/g,"**pl**");	
	return str;
}

function changeto(obj,strClass){
	if(strClass!=""){
		obj.className = strClass;
	}
	obj.style.cursor = 'hand';
}
function dropCategory(obj){
	if(obj.className == "on"){
		obj.className = "off";
		document.frmTemp.objdrop.value = "";	
	}
	else{
		obj.className = "on";
		if(document.frmTemp.objdrop.value != ""){
			identity=document.getElementById(document.frmTemp.objdrop.value);
			identity.className = "off";
		}
		document.frmTemp.objdrop.value = obj.id;
	}
}

function changeTab(n,t) {
		for (var i =1; i <= t; i ++) {
			if (i == n) {
				document.getElementById('tab'+i).className = 'current';
				document.getElementById('contentds_'+i).style.display = 'block';
			} else {
				document.getElementById('tab'+i).className = '';	
				document.getElementById('contentds_'+i).style.display = 'none';
			}			
		}
		//return false;		
	}
	
function ajaxrequest(amethod,aurl,receive,loader,request) {
	if (loader =='') { loader ='<br><center><img border="0" src="'+siteurl+'/images/loading.gif"><br>Loading...<br></center>'; }
	var xmlHttp = createxmlHttp();
	if (amethod == 1) {
		xmlHttp.open("POST",aurl, true);
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	    xmlHttp.setRequestHeader("Content-length", request.length);
	    xmlHttp.setRequestHeader("Connection", "close");
	} else {
		xmlHttp.open("GET",aurl, true);	
	}
	
	xmlHttp.onreadystatechange = function(){
				if(xmlHttp.readyState == 1 || xmlHttp.readyState == 2){
					fetch_object(receive).innerHTML = loader;
				}
				else if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
					fetch_object(receive).innerHTML = xmlHttp.responseText;
				}
			}
	if (amethod == 1) {		
		xmlHttp.send(request);
	} else {
		xmlHttp.send(null);
	}	
}

var color_picker_div = false;
var namedColors = new Array('AliceBlue','AntiqueWhite','Aqua','Aquamarine','Azure','Beige','Bisque','Black','BlanchedAlmond','Blue','BlueViolet','Brown',
	'BurlyWood','CadetBlue','Chartreuse','Chocolate','Coral','CornflowerBlue','Cornsilk','Crimson','Cyan','DarkBlue','DarkCyan','DarkGoldenRod','DarkGray',
	'DarkGreen','DarkKhaki','DarkMagenta','DarkOliveGreen','Darkorange','DarkOrchid','DarkRed','DarkSalmon','DarkSeaGreen','DarkSlateBlue','DarkSlateGray',
	'DarkTurquoise','DarkViolet','DeepPink','DeepSkyBlue','DimGray','DodgerBlue','Feldspar','FireBrick','FloralWhite','ForestGreen','Fuchsia','Gainsboro',
	'GhostWhite','Gold','GoldenRod','Gray','Green','GreenYellow','HoneyDew','HotPink','IndianRed','Indigo','Ivory','Khaki','Lavender','LavenderBlush',
	'LawnGreen','LemonChiffon','LightBlue','LightCoral','LightCyan','LightGoldenRodYellow','LightGrey','LightGreen','LightPink','LightSalmon','LightSeaGreen',
	'LightSkyBlue','LightSlateBlue','LightSlateGray','LightSteelBlue','LightYellow','Lime','LimeGreen','Linen','Magenta','Maroon','MediumAquaMarine',
	'MediumBlue','MediumOrchid','MediumPurple','MediumSeaGreen','MediumSlateBlue','MediumSpringGreen','MediumTurquoise','MediumVioletRed','MidnightBlue',
	'MintCream','MistyRose','Moccasin','NavajoWhite','Navy','OldLace','Olive','OliveDrab','Orange','OrangeRed','Orchid','PaleGoldenRod','PaleGreen',
	'PaleTurquoise','PaleVioletRed','PapayaWhip','PeachPuff','Peru','Pink','Plum','PowderBlue','Purple','Red','RosyBrown','RoyalBlue','SaddleBrown',
	'Salmon','SandyBrown','SeaGreen','SeaShell','Sienna','Silver','SkyBlue','SlateBlue','SlateGray','Snow','SpringGreen','SteelBlue','Tan','Teal','Thistle',
	'Tomato','Turquoise','Violet','VioletRed','Wheat','White','WhiteSmoke','Yellow','YellowGreen');
	
	 var namedColorRGB = new Array('#F0F8FF','#FAEBD7','#00FFFF','#7FFFD4','#F0FFFF','#F5F5DC','#FFE4C4','#000000','#FFEBCD','#0000FF','#8A2BE2','#A52A2A','#DEB887',
	'#5F9EA0','#7FFF00','#D2691E','#FF7F50','#6495ED','#FFF8DC','#DC143C','#00FFFF','#00008B','#008B8B','#B8860B','#A9A9A9','#006400','#BDB76B','#8B008B',
	'#556B2F','#FF8C00','#9932CC','#8B0000','#E9967A','#8FBC8F','#483D8B','#2F4F4F','#00CED1','#9400D3','#FF1493','#00BFFF','#696969','#1E90FF','#D19275',
	'#B22222','#FFFAF0','#228B22','#FF00FF','#DCDCDC','#F8F8FF','#FFD700','#DAA520','#808080','#008000','#ADFF2F','#F0FFF0','#FF69B4','#CD5C5C','#4B0082',
	'#FFFFF0','#F0E68C','#E6E6FA','#FFF0F5','#7CFC00','#FFFACD','#ADD8E6','#F08080','#E0FFFF','#FAFAD2','#D3D3D3','#90EE90','#FFB6C1','#FFA07A','#20B2AA',
	'#87CEFA','#8470FF','#778899','#B0C4DE','#FFFFE0','#00FF00','#32CD32','#FAF0E6','#FF00FF','#800000','#66CDAA','#0000CD','#BA55D3','#9370D8','#3CB371',
	'#7B68EE','#00FA9A','#48D1CC','#C71585','#191970','#F5FFFA','#FFE4E1','#FFE4B5','#FFDEAD','#000080','#FDF5E6','#808000','#6B8E23','#FFA500','#FF4500',
	'#DA70D6','#EEE8AA','#98FB98','#AFEEEE','#D87093','#FFEFD5','#FFDAB9','#CD853F','#FFC0CB','#DDA0DD','#B0E0E6','#800080','#FF0000','#BC8F8F','#4169E1',
	'#8B4513','#FA8072','#F4A460','#2E8B57','#FFF5EE','#A0522D','#C0C0C0','#87CEEB','#6A5ACD','#708090','#FFFAFA','#00FF7F','#4682B4','#D2B48C','#008080',
	'#D8BFD8','#FF6347','#40E0D0','#EE82EE','#D02090','#F5DEB3','#FFFFFF','#F5F5F5','#FFFF00','#9ACD32');
	
function showColorPick(f,field,fields) {
	if(!color_picker_div){
		color_picker_div = document.createElement('div');
		color_picker_div.id = 'colorPicker';
		color_picker_div.style.display='none';
		document.body.appendChild(color_picker_div);
		var contentDiv = document.createElement('div');
		contentDiv.id = 'color_picker_content';
		color_picker_div.appendChild(contentDiv);			
		createNamedColors(contentDiv);
	}
	
	if(color_picker_div.style.display=='none') { color_picker_div.style.display='block'; } else { color_picker_div.style.display='none'; }	
	color_picker_div.style.left = colorPickerGetLeftPos(f) + 'px';
	color_picker_div.style.top = colorPickerGetTopPos(f) + f.offsetHeight + 2 + 'px';
	color_picker_form_field = field;
	color_picker_form_fields = fields;
	color_picker_active_input = f;
	
}

function colorPickerGetTopPos(inputObj)
	{
		
	  var returnValue = inputObj.offsetTop;
	  while((inputObj = inputObj.offsetParent) != null){
	  	returnValue += inputObj.offsetTop;
	  }
	  return returnValue;
	}
	
function colorPickerGetLeftPos(inputObj)
	{
	  var returnValue = inputObj.offsetLeft;
	  while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
	  return returnValue;
	}
	
function createNamedColors(inputObj){
		var namedColorDiv = document.createElement('div');
		namedColorDiv.style.paddingTop = '1px';
		namedColorDiv.style.display='';
		inputObj.appendChild(namedColorDiv);
		for(var no=0;no<namedColors.length;no++){
			var color = namedColorRGB[no];
			var div = document.createElement('div');
			div.style.backgroundColor=color;
			div.innerHTML = '<span></span>';
			div.className='colorSquare';
			div.title = namedColors[no];	
			div.onclick = chooseColor;
			div.setAttribute('rgbColor',color);
			namedColorDiv.appendChild(div);				
		}
	}
	
function chooseColor()
	{
		fetch_object(color_picker_form_fields).style.backgroundColor = this.getAttribute('rgbColor');
		fetch_object(color_picker_form_field).value = this.getAttribute('rgbColor');
		color_picker_div.style.display='none';
	}
	
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function showLoading(loadbar) {
	var objLoad = fetch_object(loadbar);
	
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	
	var lightboxTop = (arrayPageSize[3] - 150) / 2;
	var lightboxAlign = (arrayPageSize[2] - 300) / 2;
		
	objLoad.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
	objLoad.style.left = (lightboxAlign < 0) ? "0px" : lightboxAlign + "px";
	objLoad.style.display ='block';
}

function hiddeContentBlock(blid) {
	if(fetch_object('block_content_'+blid).style.display == 'none') {
		fetch_object('block_content_'+blid).style.display ='block';
	} else {
		fetch_object('block_content_'+blid).style.display ='none';
	}				
}

function addBookMark(title) {
	if (window.sidebar) { // Mozilla Firefox Bookmark		
		window.sidebar.addPanel(title, document.location.href,"");	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( document.location.href, title); }	else if(window.opera && window.print) { // Opera Hotlist		
		return true; }
}

function changeSecure(aurl,receive) {
	var xmlHttp = createxmlHttp();
	xmlHttp.open("POST",aurl, true);
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", null);
	xmlHttp.setRequestHeader("Connection", "close");
	
	xmlHttp.onreadystatechange = function(){
				if(xmlHttp.readyState == 1 || xmlHttp.readyState == 2){
					fetch_object('progress_imagereg').style.display = '';
				}
				else if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
					fetch_object('progress_imagereg').style.display = 'none';
					fetch_object(receive).innerHTML = xmlHttp.responseText;
				}
			}
	
		xmlHttp.send(null);
}

function eCheckbox(fr) {
	for (var i = 0; i < fr.elements.length; i++) {
		var e = fr.elements[i];
		if ((e.checked == true) && (e.type == 'checkbox'))
			return true;
	}
	return false;
}

function eCheck(fr,la) {
	if (!eCheckbox(fr)) {
		alert(la);
		return false;	
	} else {
		return true;	
	}	
}	
