/************************************************
*
*   CEN JavaScript Framework, version 1.0
*   (c) 2008, CEN Developer Team
*
************************************************/

/* Miscellaneous */
// These functions are used to determine browsers
var CBrowser = {
	OP: function() {
		if (window.opera)
			return true;
		else
			return false;
	},
	IE: function() {
		if (document.all && !window.opera)
			return true;
		else
			return false;
	},
	FF: function() {
		if (document.getElementById && !document.all)
			return true;
		else
			return false;
	}
};

/* Validation */
var CValidation = {
  length: function(element, length) {
    return element.value.length >= length;
  },
  empty: function(element) {
    return element.value.length == 0;
  },
  isValidPhone: function(element,isPP,allow_empty) {
    /*    012-258-369 
      if (!WValidation.empty(element))
          return /\b\d{3}-\d{3}-\d{3,4}\b/.test(element.value);
      else
          return true;
    */
    if(allow_empty && (element.value == "" || element.value == null)) return true;
    var phone = element.value;
   	var phone_num = phone.replace(/\W+/g,"");
	if(isPP == true) {
    	if (phone_num.length == 9){
    		if(phone_num.match(/\D/)) {
                return false;  
    		}else {
    			return true;
    		}
    	}else {
            return false;
        }
    }
    else {
    	if (phone_num.length == 10){
    		if(phone_num.match(/\D/)) {
                return false;  
    		}else {
    			return true;
    		}
    	}else {
            return false;
        }
    } 
  },
  isPlainText: function(element, allow_empty) {
    if(allow_empty && (element.value=="" || element.value==null)) return [true, -1];
    var reg = /&|\"|>|</;
    return [!reg.test(element.value), element.value.search(reg)];
  },
  isValidEMail: function(element, allow_empty) {
    if(allow_empty && (element.value == "" || element.value == null)) return true;
    var reEmail = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/;
    return reEmail.test(element.value);
  },
  isValidUrl: function(element, allow_empty) {
    // /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
    if(allow_empty && (element.value=="" || element.value==null)) return true;
    var regExp = /^((ftp|http|https):\/\/www|www)\.*[a-z0-9_-]{1,}\.*[a-z]{2,4}\.[a-z]{2,4}\/*$/i;
    return regExp.test(element.value);
  },
  isImageFile: function(element, allow_empty) {//only gif, jpg, png
    if(allow_empty && (element.value=="" || element.value==null)) return true;
    return /\.(gif|jpg|png)$/i.test(element.value);
  },
  
  isPdfFile: function(element, allow_empty) {//only pdf
    if(allow_empty && (element.value=="" || element.value==null)) return true;
    return /\.(pdf)$/i.test(element.value);
  },
  isSwfFile: function(element, allow_empty) {//only swf
    if(allow_empty && (element.value=="" || element.value==null)) return true;
    return /\.(swf)$/i.test(element.value);
  },
  isJpgFile: function(element, allow_empty) {//only jpg
    if(allow_empty && (element.value=="" || element.value==null)) return true;
    return /\.(jpg)$/i.test(element.value);
  }
  
};

var WServerError = {
  serverNotFound: '404: No response from server.',
  serverError: 'Request failed! Please try again later.'
};

//  check for valid numeric strings	
function IsNumeric(strString)
{
   var strValidChars = "0123456789 ";
   var strChar;
   var blnResult = true;
   if (strString.length == 0) return false;
   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
   {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1){blnResult = false;}
   }
   return blnResult;
}


/* Miscellaneous */

function PrintContent(p) {
    try{ 
        var oIframe = document.getElementById('ifrmPrint');
        var oContent = document.getElementById(p).innerHTML;
        var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
        if (oDoc.document) oDoc = oDoc.document;
		oDoc.write("<html><head><title>Cambodia Express News</title>");
		oDoc.write("</head><body onload='this.focus(); this.print();'>");
		oDoc.write("<div><img src='/images/main/cen.gif?1227265038' alt='Cen'/></div>");	    
		oDoc.write(oContent + "</body></html>");	    
		oDoc.close(); 	    
    }
    catch(e){
	    self.print();
    }
}

function serverError() {
    //if($('loading').visible) $('loading').hide();
    alert(WServerError.serverError);
}

function serverNotFound() {
    //if($('loading').visible) $('loading').hide();
    alert(WServerError.serverNotFound);
}
var WScript = {};
// Add script functions. Allows for dynamic script inclusion and testing.
WScript.addScriptHandles = {};
WScript.addScriptTimers = {};

WScript.addScript = function(path, id, test, func){
	var script = document.createElement('script');
	script.src = path;
	script.id = id;
	script.type = 'text/javascript';	
	var head = document.getElementsByTagName('head').item(0);
	head.appendChild(script);
	
	var args = {};
	args.test = test;
	args.func = func;
	args.scriptId = id;
	
	if(!test[0][test[1]]){
		WScript.addScriptTimers[id] = 0;
		WScript.addScriptHandles[id] =	window.setInterval(WScript.testFunc.bind(args),200);
	}else if(func){
		func();
	}
}
WScript.testFunc = function() {
    if(WScript[this.scriptId+'_timer']>=50){
		alert('Error Adding Script! Please try again later.');
		window.clearInterval(WScript.addScriptHandles[this.scriptId]);
		WScript.addScriptTimers[this.scriptId] = null;
		document.getElementsByTagName('head')[0].removeChild($(this.scriptId));
	}
	// 'this' must be bound to this function in the setInterval call
	if(!!this.test[0][this.test[1]]){
		window.clearInterval(WScript.addScriptHandles[this.scriptId]);
		WScript.addScriptTimers[this.scriptId] = null;
		if(this.func){
			this.func();
		}
	}
	if(WScript.addScriptTimers[this.scriptId] != null){
		WScript.addScriptTimers[this.scriptId]++;
	}
}
WScript.jsPrefix = "http://localhost:3000/";

//from controls.js
WScript.fixIE = function(element, element_iefix) {
    Position.clone(element, element_iefix, {setTop:(!element.style.height)});
    element_iefix.style.zIndex = 1;
    element.style.zIndex = 1000;
    Element.show(element_iefix);
}

//req: element must be position absolute.
//fix overlapping on IE over select box
WScript.fixIEOverlapping = function(element) {
    if($(element.id + '_iefix')) {
        WScript.fixIE(element, $(element.id + '_iefix'));
    }

    if((navigator.appVersion.indexOf('MSIE')>0) 
        && (navigator.userAgent.indexOf('Opera')<0) 
        && (Element.getStyle(element, 'position') == 'absolute')
        && !$(element.id + '_iefix')) {
        new Insertion.After(element.id, 
        '<iframe id="' + element.id + '_iefix"' +
        'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
        'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');

        setTimeout(function() {
            WScript.fixIE(element, $(element.id + '_iefix'));
        }, 50);
    }
}

// this function is use to get size of cover the back path

function blanket_size(popUpDivVar) {
	if (typeof window.innerWidth != 'undefined') {
		viewportheight = window.innerHeight;
	} else {
		viewportheight = document.documentElement.clientHeight;
	}
	if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) {
		blanket_height = viewportheight;
	} else {
		if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) {
			blanket_height = document.body.parentNode.clientHeight;
		} else {
			blanket_height = document.body.parentNode.scrollHeight;
		}
	}
	var blanket = document.getElementById('blanket');
	blanket.style.height = blanket_height + 'px';
	var popUpDiv = document.getElementById(popUpDivVar);
	popUpDiv_height=blanket_height/2-350;//150 is half popup's height
	//popUpDiv.style.top = popUpDiv_height + 'px';
}

var CPopup = {
    position: 'top-left', //general property
    setPosition: function(container_id, link, position) {
        var pos = Position.cumulativeOffset(link);
        var dmDiv = {};
        dmDiv.width = $(container_id).getDimensions().width;
        dmDiv.height = $(container_id).getDimensions().height;
        var dmLink = {};
        dmLink.width = $(link.id).getDimensions().width;
        dmLink.height = $(link.id).getDimensions().height;
        if(typeof position == "undefined") {
            position = CPopup.position;
        }
        // for position = "auto-pos" it will show the popup place at the center of the screen
        if(position == "auto-pos") {
            var arrayPageScroll = getPageScroll();
	        var arrayPageSize = getPageSize();
        	$(container_id).style.left = ((arrayPageSize[0] - 35 - $(container_id).offsetWidth)/2) + 'px';
            //$(container_id).style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - $(container_id).offsetHeight) / 2) + 'px');
            $(container_id).style.top = '70px';
            
            // We use top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - $(container_id).offsetHeight) / 2) + 'px');
            // because we use "position:absolute" but when user scroll it's position will change follow the scroll
            // We use top='70px' because we use "position:fixed" in order to keep this position when user scroll
            
        }
        else if(position == "center") {
            if (typeof window.innerWidth != 'undefined') {
        		viewportwidth = window.innerHeight;
        	} else {
        		viewportwidth = document.documentElement.clientHeight;
        	}
        	if ((viewportwidth > document.body.parentNode.scrollWidth) && (viewportwidth > document.body.parentNode.clientWidth)) {
        		window_width = viewportwidth;
        	} else {
        		if (document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth) {
        			window_width = document.body.parentNode.clientWidth;
        		} else {
        			window_width = document.body.parentNode.scrollWidth;
        		}
        	}
        	window_width=(window_width/2)-550; //this the half with of container
        	$(container_id).style.left = window_width+"px";
        	$(container_id).style.top = pos[1] + 15 + "px";
        }
        else if(position == "bottom-left") {
            $(container_id).style.left = pos[0] + "px";
            $(container_id).style.top = pos[1] + 15 + "px";
        }
        else if(position == "top-left") {
            $(container_id).style.left = pos[0] + "px";
            $(container_id).style.top = pos[1] - dmDiv.height - 5 + "px";
        }
        else if(position == "top-right") {
            $(container_id).style.left = pos[0] - dmDiv.width + dmLink.width + "px";
            $(container_id).style.top = pos[1] - dmDiv.height - 5 + "px";
        }
        else { //bottom-right
            $(container_id).style.left = pos[0] - dmDiv.width + dmLink.width + "px";
            $(container_id).style.top = pos[1] + 15 + "px";
        }
        if(parseInt($(container_id).style.left) < 0) {
            $(container_id).style.left = "0px";
        }
        if(parseInt($(container_id).style.top) < 0) {
            $(container_id).style.top = "0px";
        }
        /*var posDiv = [];
        posDiv[0] = parseInt($(container_id).style.left);
        posDiv[1] = parseInt($(container_id).style.top);
        if(pos[0] > posDiv[0] && pos[0] < posDiv[0] + dmDiv.width && pos[1] > posDiv[1] && pos[1] < posDiv[1] + dmDiv.height) {
            $(container_id).style.left = pos[0] + dmLink.width + "px";
        }*/
    },
}

function showCarIn(pic,id_pic,path_car) { 
    document.getElementById(id_pic).src='/images/car/'+path_car+'/' + pic; 
    new Effect.Opacity(
       id_pic, { 
          from: 0.0, 
          to: 1.0,
          duration: 1.0
       }
    );
} 

isNA = function(t) {
    var result = "";
    if(t == "" || t == null)
        result = 'N/A'
    else
        result = t
    return result;
}


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;
}

page_path = function(filename) {
     return "/images/admin/upload/icon/" + filename
}
goods_path = function(filename) {
     return "/images/admin/upload/goods_icon/" + filename
}

flash_write0 = function(file, width, height) {
    document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' +
    ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"' +
    ' width="'+width+'" height="'+height+'" id="movie" ><param name="movie" value="'+file+'" />' +
    ' <param name="wrmode" value="transparent" /><param name="menu" value="false" />' +
    ' <!--[if !IE]> <--> <object type="application/x-shockwave-flash"' + 
    ' data="'+file+'" width="'+width+'" height="'+height+'"></object>' + 
    '<!--> <![endif]--></object>');
} 

flash_write1 = function(file, width, height) {
    document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' +
        ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"' +
        ' width="'+width+'" height="'+height+'" id="movie" ><param name="movie" value="'+file+'" />' +
        ' <param name="wmode" value="transparent" /><param name="menu" value="false" />' +
        ' <!--[if !IE]> <--> <object wmode="transparent" type="application/x-shockwave-flash"' +
        ' data="'+file+'" width="'+width+'" height="'+height+'"></object>' +
        '<!--> <![endif]--></object>');
} 



