//Data Grid functions
function DynamicDataGrid(formName) {
	this.formName = formName;
	this.rowName = "chk";
	this.pageSize = 10;
}

DynamicDataGrid.prototype={
	selectAll: function(){
	//check all checkboxes
		var doc = document.getElementsByName(this.formName+"_"+this.rowName+"[]");
		for(i=0;i<doc.length;i++){
			doc[i].checked = true;
		}
	},
	selectNone: function(){
	//deselect all
		var doc = document.getElementsByName(this.formName+"_"+this.rowName+"[]");
		for(i=0;i<doc.length;i++){
			doc[i].checked = false;
		}
	},
	selectInvert: function(){
	//invert selection
		var doc = document.getElementsByName(this.formName+"_"+this.rowName+"[]");
		for(i=0;i<doc.length;i++){
			doc[i].checked = !doc[i].checked;
		}
	},
	getItems: function(){
	//get all rows with their status (checked, unchecked)
		var frmData = document.forms[this.formName];

		lst = frmData.elements;

		rows = new Array();
		selectedItemCount = 0;
		for (i=0; i<lst.length; ++i)
		{

			if (lst[i].name==this.formName+"_"+this.rowName+"[]"){
				if (lst[i].checked){
					rows[lst[i].value] = 1;
					selectedItemCount = selectedItemCount + 1;
				}
				else{
					rows[lst[i].value] = 0;
				}
			}
		}
		retVal = new Array();
		retVal["rows"] = rows;
		retVal["selected_item_count"] = selectedItemCount;
		return retVal;
	},
	getCount: function(){
	//total items
		var items = this.getItems();
		return items["rows"].length;
	},
	getSelecedCount: function(){
	//total items
		var items = this.getItems();
		return items["selected_item_count"];
	},
	refresh: function (){
	//refresh datagrid
		var frmData = document.forms[this.formName];

		if (frmData == undefined || !frmData.cur_page){
			cur_page=1;
		}
		else{
			cur_page = frmData.cur_page.value;
		}
		this.loadPage(cur_page,this.pageSize);
	},
	changePageSize: function(newPageSize){
		this.pageSize = newPageSize;
		this.refresh();
	}
};

function isEnterPressed(event){
	var browser = navigator.appName
	//alert(browser)
	if(browser == "Netscape")
		var keycode = event.which;
	else
		var keycode = window.event.keyCode;

	if(keycode == 13){
		return true;
	}
	return false;
}

function popWin(url,width,height,windowName,scrollbar,content){
	var x=(screen.width)?(screen.width-width)/2:100;
	var y=(screen.height)?(screen.height-height)/2:100;

	var features="width="+width+"px,height="+height+"px, top="+y+"px, left="+x+"px";
		features+=(scrollbar)?",scrollbars="+scrollbar:"";
	if (!windowName){
		windowName="untitled";
	}
	var popWindow=window.open(url, windowName, features);

	if (content!=""){
		popWindow.document.write(content);
	}
	if (document.layers){
		window.moveTo(x, y);
	}
	popWindow.focus();
}

function popWinEx(url,width,height,windowName,scrollbar,content){
	var winSize = getWindowSize();
	if (width == 0) {
		width = screen.width;
	}

	if (height == 0){
		height = screen.height;
	}

	popWin(url,width,height,windowName,scrollbar,content);
}

// add new option to selectbox
function addOption(selectboxId, val, txt)
{
        var objOption = new Option(txt,val);

        document.getElementById(selectboxId).options.add(objOption);
}

function loadProductTypes(groupId){
	document.getElementById('product_order_type_loading').innerHTML="<img src='/images/misc/loading.gif'/>";
	xajax_getProductOrderTypesOfGroup(groupId,'product_order_type_id','product_order_type_loading');
}
function loadPageSides(){
	document.getElementById('page_side_loading').innerHTML="<img src='/images/misc/loading.gif'/>";
	frmData = document.frm_price_calculator;
	groupId = frmData.group_id.value;
	productOrderTypeId = frmData.product_order_type_id.value;
	xajax_getPageSides(groupId,productOrderTypeId,'page_side_id','page_side_loading');
}

function loadProductSizes(){
	document.getElementById('product_size_loading').innerHTML="<img src='/images/misc/loading.gif'/>";
	frmData = document.frm_price_calculator;
	groupId = frmData.group_id.value;
	productOrderTypeId = frmData.product_order_type_id.value;
	pageSideId = frmData.page_side_id.value;
	xajax_getProductSizes(groupId,productOrderTypeId,pageSideId,'product_size_id','product_size_loading');
}
function loadProductStocks(){
	document.getElementById('product_stock_loading').innerHTML="<img src='/images/misc/loading.gif'/>";
	frmData = document.frm_price_calculator;
	groupId = frmData.group_id.value;
	productOrderTypeId = frmData.product_order_type_id.value;
	pageSideId = frmData.page_side_id.value;
	productSizeId = frmData.product_size_id.value;
	xajax_getProductStocks(groupId,productOrderTypeId,pageSideId,productSizeId,'product_stock_id','product_stock_loading');
}
function loadProductOrderMinimumQuantity(){
	document.getElementById('min_quantity_loading').innerHTML="<img src='/images/misc/loading.gif'/>";
	frmData = document.frm_price_calculator;
	groupId = frmData.group_id.value;
	productOrderTypeId = frmData.product_order_type_id.value;
	pageSideId = frmData.page_side_id.value;
	productSizeId = frmData.product_size_id.value;
	productStockId = frmData.product_stock_id.value;
	xajax_getProductOrderMinimumQuantity(groupId,productOrderTypeId,pageSideId,productSizeId,productStockId,'min_quantity_loading');
}

function select_deselectAll(val){
	var chkBoxes = document.getElementsByTagName("input");
		for(i=0;i<chkBoxes.length;i++){
			if (chkBoxes[i].type=='checkbox'){
				chkBoxes[i].checked = val;
			}
		}
}

function selectInvert(){
	var chkBoxes = document.getElementsByTagName("input");
		for(i=0;i<chkBoxes.length;i++){
			if (chkBoxes[i].type=='checkbox'){
				chkBoxes[i].checked = !chkBoxes[i].checked;
			}
		}
	}

function doDelete(currentPage, pageSize, templateFile){
	if (confirm('Are you sure you want to delete?')){
		var chkBoxes = document.getElementsByTagName("input");
		rows = new Array();
		selectedItemCount = 0;
		for (i=0; i<chkBoxes.length; ++i)
		{
			if (chkBoxes[i].type=='checkbox'){
				if (chkBoxes[i].checked){
					rows[chkBoxes[i].value] = 1;
					selectedItemCount = selectedItemCount + 1;
				}
				else{
					rows[chkBoxes[i].value] = 0;
				}
			}
		}
		items = new Array();
		items["rows"] = rows;
		items["selected_item_count"] = selectedItemCount;
		xajax_doDelete(items, currentPage, pageSize, xajax.getFormValues('product_packaging_search'), templateFile);
		return true;
	}
}

function changeClass(ID, className){
	window.document.getElementById(ID).className=className;
}
function changeClassDefault(ID){
	window.document.getElementById(ID).className="";
}

function getOptionTitle(selectObj){
	if (selectObj.selectedIndex && selectObj.selectedIndex >= 0){
		return selectObj.options[selectObj.selectedIndex].text;
	} else {
		return "";
	}
}

function updateObjTitle(selectObj, objTitleId){
	var objTitle = document.getElementById(objTitleId);

	if (objTitle == null){
		var objs = document.getElementsByName(objTitleId);
		if (objs != null) { objTitle = objs[0]}
	}

	//get selectObj
	selectObj=(typeof selectObj=="object")?selectObj:
		(typeof selectObj=="string")?document.getElementById(selectObj):null;

	if (objTitle != null && selectObj != null){
		if (selectObj.value != ""){
			objTitle.value = selectObj.options[selectObj.selectedIndex].text;
		} else {
			objTitle.value="";
		}
	}
}

function showIconLoading(id){
	
	var div_holder = document.getElementById(id);
	
	if(div_holder == null)
	{
		div_holder = document.getElementById('filter_state_loading');
	}
	
	div_holder.innerHTML="<img src='/images/misc/loading.gif'/>";
	
}

function setupCalendar(fieldName, buttonName){
	Calendar.setup({
	inputField     :    fieldName,     // id of the input field
	ifFormat       :    "%m/%d/%Y",      // format of the input field
	button         :    buttonName,  // trigger for the calendar (button ID)
	align          :    "Br",           // alignment (defaults to "Bl")
	singleClick    :    true
	});
}

function NumberOnly(ele) {
	if (!/^\d*$/.test(ele.value)) {
		ele.value = ele.value.replace(/[^\d]/g,"")
	}
}

function isNumber(event){

	var re = /^[0-9 ]$/;
	var browser = navigator.appName
	//alert(browser)
	if(browser == "Netscape")
		var keycode = event.which
	else
		var keycode = window.event.keyCode

	if(keycode != 13 && keycode != 0 && keycode != 8){
		strKeyCode = String.fromCharCode(keycode);
		//alert(keycode)
		if(strKeyCode.search(re)) return false;
		else return true;
	}
	return true;
}

function isZipCode(event){

	var re = /^[0-9 -]$/;
	var browser = navigator.appName
	//alert(browser)
	if(browser == "Netscape")
		var keycode = event.which
	else
		var keycode = window.event.keyCode

	if(keycode != 13 && keycode != 0 && keycode != 8){
		strKeyCode = String.fromCharCode(keycode);
		//alert(keycode)
		if(strKeyCode.search(re)) return false;
		else return true;
	}
	return true;
}

function onEnter(e, function_txt){
	var key;
	if(window.event)
		key = window.event.keyCode;
	else
		key = e.which;


	if (key == 13) {
		eval(function_txt);
	}
}

// Format date is mm/dd/yyyy hh:mm:ss
function isExpired(dateCheck, hours, minutes){
	var days = 0;
	var difference = 0;

	dateCheckObj = new Date(dateCheck); // this is date inputed
	todayObj = new Date(); //today

	difference = dateCheckObj - todayObj;
	expminutes = Math.round(difference/(1000*60)); // compute minutes
	expminutes -= 60*hours;  //expires in some hours
	expminutes -= minutes; //expires in some minutes

	if (expminutes < 0) {
		//alert("The time you have chosen has already passed.");
		return true;
	} else {
		return false;
	}
}

function getWindowSize() {
  var myWidth = 700, myHeight = 500;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  //window.alert( 'Width = ' + myWidth );
  //window.alert( 'Height = ' + myHeight );
  return {width:myWidth, height:myHeight};
}

function fillFormData(formName, arr){
	if (typeof arr == "string"){
		// This is json param
		arr = eval('('+arr+')');
	}
	var frm = document.forms[formName];
	if (frm != null){
		for (key in arr){
			if (frm[key] != null){
				frm[key].value = arr[key];
			}
		}
	}
}

function emptyFormData(formName){
	$('#'+formName+' :input').val("");
	//$('#'+formName').clearFields();
}

function emptyFormDataEx(formName){
	var frm = document.forms[formName];
	clearFields(frm);
}

function isVisible(elem){
  while(elem) {
    if(elem.style.display == 'none')
      return false;
	elem = elem.parentElement;
  }

  return true;
}

/* Form plugin JQuery
  Using:
  clearFields(element);
  For form, we can use reset function: form.reset();
*/
function clearFields(element) {

  // iterate over all of the inputs for the element
  // element that was passed in
  $(':input', element).each(function() {
    var type = this.type;

    var tag = this.tagName.toLowerCase(); // normalize case
    //var disabled = (typeof this.disabled != 'undefined');
    // it's ok to reset the value attr of text inputs,
    // password inputs, and textareas
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = "";
    // checkboxes and radios need to have their checked state cleared
    // but should *not* have their 'value' changed
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    // select elements need to have their 'selectedIndex' property set to -1
    // (this works for both single and multiple select elements)
    else if (tag == 'select')
      this.selectedIndex = 0;
  });
};

function addComma(str){
	if (str != "") { return ", "+ str; }
	return "";
}

function addLine(str, prefix){
	if (str != "") { return "<br /> "+ prefix + str; }
	return "";
}

function _isFBO(triptype, ispickup){

	if (ispickup && (triptype == 5)){
		// FBO pickup off
		return true;
	}

	if (!ispickup && (triptype == 6)){
		// FBO drop off
		return true;
	}

	return false;
}

function _isAddress(triptype, ispickup){

	if (triptype == 1 || triptype == 0) { // Point to Point
		return true;
	}

	if (ispickup && (triptype == 3 || triptype == 4 || triptype == 6)){
		// Dropoff Airport, As Directed, FBO drop off
		return true;
	}

	if (!ispickup && (triptype == 2 || triptype == 5)){
		// Pickup Airport, FBO pickup
		return true;
	}

	return false;
}

function _isAirport(triptype, ispickup){
	if (triptype == 1 || triptype == 0) { // Point to Point
		return false;
	}

	if (ispickup && (triptype == 2)){
		// Pickup Airport
		return true;
	}

	if (!ispickup && (triptype == 3)){
		// Dropoff Airport
		return true;
	}

	return false;
}

function combineLocation(triptype, ispickup, add1, add2, city, state, zip,
			airport, airline, flight_num, airport_city,
			fbo_name, fbo_phone, tail){
	var combine = "";
	if (_isAddress(triptype, ispickup)){
		combine = buildAddress(add1, add2, city, state, zip);
	}
	else if (_isFBO(triptype, ispickup)){
		combine = buildFBO(add1, add2, city, state, zip, fbo_name, fbo_phone, tail);
	}
	else if (_isAirport(triptype, ispickup)){
		combine = buildAirport(airport, airline, flight_num, airport_city);
	}

	return combine;
}

function getRealLocation(triptype, ispickup, add1, add2, city, state, zip, airport){
	var combine = "";
	if (_isAddress(triptype, ispickup) || _isFBO(triptype, ispickup)){
		combine = buildAddress(add1, add2, city, state, zip);
	} else if (_isAirport(triptype, ispickup)){
		combine = airport;
	}

	return combine;
}

function buildAirport(airport, airline, flight_num, city){
	var result = airport;
	result = result + addLine(airline, 'Line: ');
	result = result + addLine(flight_num, 'Flight: ');
	result = result + addLine(city, '');
	return result;
}

// Combine Address
function buildAddress(add1, add2, city, state, zip){
	var combine = "";
	if (add1 != "") {
		combine = add1+addComma(add2);

			if (city != "" && state != "") {
				combine =combine+ ", "+city+' - '+state;

			} else if (city != "" || state != ""){
				//Only city or state not empty
				combine =combine+ ", "+city+state;
			}

			combine=combine+addComma(zip);
	}

	return combine;
}

// Combine FBO
function buildFBO(add1, add2, city, state, zip, fbo_name, fbo_phone, tail){
	var combine = "";
	if (add1 != "") {
		combine = add1+addComma(add2);

		if (city != "" && state != "") {
			combine =combine+ ", "+city+' - '+state;

		} else if (city != "" || state != ""){
			//Only city or state not empty
			combine =combine+ ", "+city+state;
		}

		combine=combine+addComma(zip);
		combine=combine+'<br>FBO Name: '+fbo_name;
		combine=combine+'<br>FBO Phone: '+fbo_phone;
		combine=combine+'<br>FBO Tail: '+tail;
	}

	return combine;
}

function hideElement(el){
	if(el.style){
		el.style.display = "none";
	}
	clearFields(el);
}

function enableElement(el){
	if(el.style){
		el.style.display = "";
	}
}

Array.prototype.contains = function (element) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == element) {
			return true;
		}
	}
	return false;
}

// Change date object to string mm/dd/yyyy
Date.prototype.toMMDDYYYY=function(){
	var dd=this.getDate();
	if(dd<10) dd='0'+dd;
	var mm=this.getMonth()+1;
	if(mm<10) mm='0'+mm;
	var yyyy=this.getFullYear();
	return String(mm+"/"+dd+"/"+yyyy);
};

function view_map_admin(from, to){
	view_map(from, to, '/admin');
}

function view_map(from, to, path){
	if (from == ""){
		alert(' Pickup Location is emptied.');
	} else {
		popWin(path + '/direction.php?from='+from + '&to='+to, 930, 680, 'Map', 'no', '');
	}
}

function showPopWinEx(url, width, height, header, returnFunc) {
	var winSize = getWindowSize();
	if (width == 0) {
		width = winSize.width-40;
	}

	if (height == 0){
		height = winSize.height-40;
	}

	showPopWin(url, width, height, header, returnFunc);
	window.scrollBy(0,1);
	window.scrollBy(0,-1);
}

function _hourUpdated(){
	var hour = document.getElementById("hours").value;
	var minute = document.getElementById("minutes").value;
	var ampm = document.getElementById("ampm").value;
	var hourExplainObj = document.getElementById("hourExplain");

	hour = parseInt(hour);
	hour = getHour24(hour, ampm);


	hourExplainObj.innerHTML = '('+hour+':'+minute+')';
}

/*
	value = 1-100
	name = percent name + '100'
	formName: if empty, then get object by id name
*/
function updatePercentObject(value, name, formName) {

	//alert("Form Name: "+formName);

	var percentObj;

	if (formName == ''){
		percentObj = document.getElementById(name.substr(0 , name.length-3));
	} else {
		percentObj = document.forms[formName][name.substr(0 , name.length-3)];
	}

	//alert("Variable Name: "+percentObj.name);

	var paramValue = parseFloat(value);
	if (isNaN(paramValue)){
		paramValue = 0.0;
	}

	if (paramValue > 0) {
		percentObj.value = (paramValue/100.0);
	} else {
		percentObj.value = 0.0;
	}

	//alert("Updated Value: "+percentObj.value);

}

/**
*
*  Javascript trim, ltrim, rtrim
* http://www.webtoolkit.info/javascript-trim.html
*
**/


function trim_space(str) {
	return trim(str, ' ');
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function logoutFromDialog(){
	window.top.hidePopWin();
	window.top.location.href = "/admin/logout.php";
}

function formatNumber(nStr)
{
	nStr += '';
	var x = nStr.split('.');
	var x1 = x[0];
	var x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}

	return x1 + x2;
}

/*
	Note: Javascript seem don't accept function with prefix is print. So I use function name is prntDiv
	divId: id of span or div...
*/
function prntDiv(divId)
{
   var divToPrint=document.getEelementById(divId);
  newWin= window.open("");
  newWin.document.write(divToPrint.outerHTML);
  newWin.print();
  newWin.close();
}

// Return acctual hour number from hour number AM/PM
function getHour24(hourNum, ampm){
	// 12AM = 0h.
	// 12PM = 12h.
	if (hourNum == 12){
		hourNum = 0;
	}

	if (ampm == 'PM'){
		hourNum += 12;
	}

	return hourNum;
}
