/*
 *------------------------------------------------------*
 * File    	   : script.js           		*
 * @Author 	   : Anju S B	 	             	*
 * @created on     : 27-12-2010      			*
 * @updated on     : 27-12-2010	     		   	*
 * @copyright 2010 Keltron			     	*
 *------------------------------------------------------*

 * This file is for all validation of input field
*/

//192.168.1.19
//var paths = "http://192.168.1.19/hcms/hcms_site/";	//Path Of the Application
var paths = "http://sc.keltron.org/";	//Path Of the Application
var xmlHttp;


/************************#   General Function   #*****************************/

//General Validation
function commonValidate(fld,vals,msg,msgdispId){ 
        var ids    = '#'+fld; 
	var getVal = $(ids).val(); 
	//getVal   = getVal.trim();    
	getVal     = trimData(getVal);

	if (getVal == vals){
		if (msg)  $(msgdispId).html(msg);  
		$(ids).focus(); 
		return false;
	} 
	else{
	    $(msgdispId).html(""); 
	    return true;	
	}
}

//Generala trim 
function trimData(s){
     return s.replace(/^\s+|\s+$/g, "");
}

//Email Validation using RE
function validateEmail(elementValue){  		
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
    return emailPattern.test(elementValue);  
}

//validate mobile number
function validateMobs(mobId,dispId){
	if ($(mobId).val().length!=10) {
			$(dispId).html('Invalid Mobile Number!');
			$(mobId).focus();
			return false;
	}
	if(!$(mobId).val().match('^(0|[1-9][0-9]*)$')){
		$(dispId).html('Mobile Phone Number should be Numbers!');
		$(mobId).focus();
		return false;
	}
        return true;
}

//Post Ajax function
function GetXmlHttpObject(){
	var xmlHttp=null;
	try	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
 	}
	catch (e) 	{
		//Internet Explorer
 		try
  		{
  			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  		}
 		catch (e)
  		{
  			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  		}
 	}
	return xmlHttp;
}


function dataPostForm(url,param,postn,msgid,opnType,hdFld){	
	var http = GetXmlHttpObject();
	http.open("POST", url, true);

	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", param.length);
	http.setRequestHeader("Connection", "close");

	http.onreadystatechange = function() {//Call a function when the state changes.
	   if(http.readyState == 4 && http.status == 200) {

		var resp = http.responseText; 
		if (opnType == 'ComboFill'){
			if (resp)	$(msgid).html(resp); 
		}
		else if (opnType == 'School Code'){ //Value need
		   if (postn.value != "") {
			if (!resp)	$(msgid).html(hdFld+' doesn`t Exist!'); 
			else $(msgid).html(''); 
			if (!resp && postn)	postn.focus();		
		   }		   	
		}
		else {			//must be unique value
			//alert(resp);
			if (resp)	$(msgid).html(resp); 
			else $(msgid).html(''); 

			if (resp && postn)	postn.focus();			
			if (opnType == 'DEL'){
				alert(resp);
				var sURL = unescape(window.location.pathname);
				window.location.href = sURL;
			}
		}	
		
		$("#loadImg").html("");
	   }
	   else {
		$("#loadImg").html("");//<img src='../images/load.gif' border=0>
	   }
	} 

	http.send(param);	
}

//Function for checking values available
function valueAvailable(tab,fld,the,msgids){
	var url=paths+"Administrator/ajaxScript.php";
	var params = "oprn=valueAvilability&table="+tab+"&flds="+fld+"&vals="+the.value; 
	dataPostForm(url,params,the,msgids,'','');
}

//function fillComboOnly
function fillCombo(tab,condFlf,the,dispHtml,valId,valName,ordBy,cmbName){ 
	var url=paths+"Administrator/ajaxScript.php";
	var params = "oprn=fillCombo&table="+tab+"&condFlf="+condFlf+"&condVal="+the.value+"&valId="+valId+"&valName="+valName+"&ordBy="+ordBy+"&cmbName="+cmbName;
	dataPostForm(url,params,the,dispHtml,'fillCombo',''); 
}



//function To display ModelNumber
function FillModelNumber(cmb_prod_id,cmb_prodCatg_id,cmb_prodType_id,cmb_make_id,cmb_supplier_id,cmb_sp_id,dispHtml){ 

	var prod_id = "";
	var sp_id   = "";

	if (cmb_prod_id != "")
		prod_id 	= $(cmb_prod_id).val();
	var prodCatg_id = $(cmb_prodCatg_id).val();
	var prodType_id = $(cmb_prodType_id).val();
	var make_id 	= $(cmb_make_id).val();
	var supplier_id = $(cmb_supplier_id).val();
	if (cmb_sp_id != "")
		sp_id	= $(cmb_sp_id).val();


	
	var url=paths+"Administrator/ajaxScript.php";

	var params = "oprn=fillModelNo&prod_id="+prod_id+"&catg_id="+prodCatg_id+"&type_id="+prodType_id+"&make_id="+make_id+"&supplier_id="+supplier_id+"&sp_id="+sp_id; 	
	dataPostForm(url,params,'',dispHtml,'ComboFill',''); 
}





//Function to fill role and make or supplier Details
function fillSelectBoxMakeSupplr(tab,dispId,sel_id,sel_val,cond_fld,ordBy,primKey,the,splCase,label,combo_name){
	if (the.value == 5)   {
		$("#dispSupplier").hide();
		$("#dispSP").hide();
		$("#dispMake").show();
	}
	else if (the.value == 6){
		$("#dispSupplier").show();
		$("#dispSP").hide();
		$("#dispMake").hide();
	}
	else {
		$("#dispSupplier").hide();
		$("#dispSP").show();
		$("#dispMake").hide();
	}

	fillSelectBox(tab,dispId,sel_id,sel_val,cond_fld,ordBy,primKey,the,splCase,label,combo_name)
}
//Function for Cobo Box data from database
function fillSelectBox(tab,dispId,sel_id,sel_val,cond_fld,ordBy,primKey,the,splCase,label,combo_name){
	var url=paths+"Administrator/ajaxScript.php";
	var params = "oprn=fillSlect&table="+tab+"&selId="+sel_id+"&selVal="+sel_val+"&condFld="+cond_fld+"&condVal="+the.value+"&ordBy="+ordBy+"&primK="+primKey+"&opnChk="+splCase+"&label="+label+"&cmbName="+combo_name;

	dataPostForm(url,params,the,dispId,'',''); 

}

//User group subgroup display
function subgroup_userrole(the){ 
	if (the) {
		var url=paths+"Administrator/ajaxScript.php";
		var param = "oprn=subgroup_userrole&groupId="+the;
		var http = GetXmlHttpObject();
		http.open("POST", url, true);
		//Send the proper header information along with the request
		http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http.setRequestHeader("Content-length", param.length);
		http.setRequestHeader("Connection", "close");

		http.onreadystatechange = function() {//Call a function when the state changes.
	   		if(http.readyState == 4 && http.status == 200) {
				var resp      = http.responseText; 	 //alert(resp);
				var respSplit = resp.split("$$");
				$("#subgroupTr").html(respSplit[0]);
				$("#roleTr").html(respSplit[1]);
	   		}	  
		} 
		http.send(param);		
	} else alert("Select User Group!");
}

//Delete Items
function deleteItems(tab,fld,val,dispId,the){ 
	if (confirm("Do you want to Delete?")) {
		var url=paths+"Administrator/ajaxScript.php";
		var params = "oprn=delItem&table="+tab+"&filds="+fld+"&vals="+val;
		dataPostForm(url,params,'',dispId,'DEL','');
	}
	else return false;
}






//Function school code avilable

function codeAvailbe(tab,fld,the,msgids,chkfld){  
	var url=paths+"Administrator/ajaxScript.php";
	var params = "oprn=valueAvilability&table="+tab+"&flds="+fld+"&vals="+the.value; 
	dataPostForm(url,params,the,msgids,'School Code',chkfld);
}

/*
//Edit Details display
function editData($ids,disId,imgId,funName){
	
}
*/


/*
function fillSelectBox(tab,fldVal,fldId,the,dispId,orderby,tabId,idVal){
	var url=paths+"Administrator/ajaxScript.php";
	var params = "oprn=fillSlect&table="+tab+"&fldV="+fldVal+"&fldId="+fldId+"&ordBy="+orderby+"&tabId"+tabId+"&tabVa"+tabId;
	dataPostForm(url,params,the,dispId);

}
*/
/*****************************************************************************/
/************************#   Jquery Functions   #*****************************/



$(document).ready(function(){ 

// To change the input box border color on click 
/*
	$("input").click(function() {
   		$("input").css("border-color","");
   		$(this).css("border-color","#e14a4a");

  	});
*/


 $(":text, textarea").blur(function() { 
        var text = "";
        var arr = $(this).val()
        $.each(arr, function(i) {
            var c = arr.charAt(i); 
            if ((c == "'"))   // || (c == '"')
               text += '`';
	    else  text += c;
		
        });
        $(this).val(text);
    });

// To check repeated values in the text box
/*$(".noRepeat").change(function() {
    alert("dd");
    var $current = $(this);

    $(".noRepeat").each(function() {
        if ($(this).val() == $current.val() && $(this).attr('id') != $current.attr('id'))
        {
            alert('duplicate found!');
        }

    });
  });*/




/*
 $("input").blur(function() { 
alert("dd1");
    var $current = $(this);
    $('input[name^="text"]').each(function() {
        if ($(this).val() == $current.val() && $(this).attr('id') != $current.attr('id'))
        {
            alert('duplicate found!');
        }

    });
 });
*/
// To validate index field values      	


  	$('#login').click(function() {
		if(!commonValidate('uname','','Username Required!','#msgDisp')) return false;
		if(!commonValidate('passwd','','Password Required!','#msgDisp')) return false;
 	});

//Validate Register User save
	$('#saveReg_user').click(function() { 
		if(!commonValidate('district_id','','District Required!','#msgDispl')) return false;
		if(!commonValidate('school_typ_id','','School Type Required!','#msgDispl')) return false;
		if(!commonValidate('school_name','','School Name Required!','#msgDispl')) return false;

		if(!commonValidate('first_name','','Name Required!','#msgDispl')) return false;
		if(!commonValidate('username','','Username Required!','#msgDispl')) return false;
		if(!commonValidate('pwd','','Password Required!','#msgDispl')) return false;
		if(!commonValidate('cpwd','','Confirm Password Required!','#msgDispl')) return false;
		if ($("#cpwd").val() != $("#pwd").val()){
			$("#msgDispl").html('Invalid Confirm Password!');
			$("#cpwd").focus();
			return false;			
		}

		if(!commonValidate('email','','Email Required!','#msgDispl')) return false;
		var emailID = document.getElementById("email").value; 	
		if (validateEmail(emailID) == false){
			$("#msgDispl").html('Invalid EmailId!');
			$("#email").focus();
			return false;
		}
		if(!commonValidate('mobile_no','','Phone Number Required!','#msgDispl'))return false;
		if ($('#mobile_no').val().length!=10) {
			$("#msgDispl").html('Invalid Mobile Number!');
			$("#mobile_no").focus();
			return false;
		}

		if(!$('#mobile_no').val().match('^(0|[1-9][0-9]*)$')){
			$("#msgDispl").html('Mobile Phone Number should be Numeric Type!');
			$("#mobile_no").focus();
			return false;
		}
		if (confirm("Do you want to continue?")) return true;
		else return false;
	});

// To validate user 
	$('#save_user').click(function() { 

		if (document.getElementById('custGrp_id') != null){
			if(!commonValidate('custGrp_id','','Customer Group Required!','#msg_cust_group')) return false;
		}
		if (document.getElementById('school_code') != null){
			if(!commonValidate('school_code','','School code Required!','#msg_schCode')) return false;
		}

		//if ($('#custGrp_id') == null|| $('#custGrp_id')=="undefined") {alert("Y"); alert($('#custGrp_id'));}
                //else alert("N");

		if(!commonValidate('first_name','','Name Required!','#msg_first_name')) return false;
		if(!commonValidate('username','','Username Required!','#msg_username')) return false;
		if(!commonValidate('pwd','','Password Required!','#msg_pwd')) return false;
		if(!commonValidate('cpwd','','Confirm Password Required!','#msg_cpwd')) return false;
		if ($("#cpwd").val() != $("#pwd").val()){
			$("#msg_cpwd").html('Invalid Confirm Password!');
			$("#cpwd").focus();
			return false;			
		}
		if(!commonValidate('district_id','','District Required!','#msg_district')) return false;
		if(!commonValidate('email','','Email Required!','#msg_email')) return false;
		var emailID = document.getElementById("email").value; 	
		if (validateEmail(emailID) == false){
			$("#msg_email").html('Invalid EmailId!');
			$("#email").focus();
			return false;
		}

		if (!validateMobs("#mobile_no","#msg_mobile_no")) return false;


		if(!commonValidate('landph_no','','Phone Numner Required!','#msg_mobile_no') && !commonValidate('mobile_no','','Phone Number Required!','#msg_mobile_no'))return false;

		if (confirm("Do you want to continue?")) return true;
		else return false;
	});


//Validate Group Name
	$('#save_group').click(function() {
		if(!commonValidate('group_name','','Group Name Required!','#msg_grpName')) return false;
		if (confirm("Do you want to Save?")) return true;
		else return false;
	});
//Validate Group Name
	$('#save_role').click(function() { 
		if(!commonValidate('group_id','','Group Name Required!','#msg_Name')) return false;
		if(!commonValidate('role_name','','Role Name Required!','#msg_Name')) return false;
		if (confirm("Do you want to Save?")) return true;
		else return false;
	});
//****************************************


//........................
//Toggle Product Display  
$('#faultval').hide();
$('#faultDisp').click(function() {
	 $('#faultval').slideToggle('slow');
	 $('#addmore').hide();
});

//Toggle add more fault Display  
$('#addmore').hide();
$('#addmoreImg').click(function() {
	 $('#addmore').slideToggle('slow');
});

//Toggle Product Details
$('#prodDetails').hide();
$('#headMsg').click(function() {
	 if ($("#headMsg").html() == "Hide Product Details")
	 	$("#headMsg").html("Show Product Details");
	 else 	$("#headMsg").html("Hide Product Details");
	 $('#prodDetails').slideToggle('slow');

for(i=0;i<$("#countProduct").html();i++){
	var FIds = '#'+'faultDisp'+i; 
	$(FIds).hide();
}
});


/*
$("#compStatusBtn").click(function(){ alert("ddd");

	 if ($("#compStatusBtn").html() == "Hide")
	 	$("#compStatusBtn").html("Show");
	else $("#compStatusBtn").html("Hide");
	$('#CompStatusDisp').slideToggle('slow');
});*/
//******************************************
// Next

});


/*****************************************************************************/
/************************#   Special Functions   #******************************/

//Validate MyAccount Update details
function validateMyaccount() { 

		if(!commonValidate('My_name','','Name Required!','#msgDispl')) return false;
		if(!commonValidate('My_address1','','Address Required!','#msgDispl')) return false;
		if(!commonValidate('My_place','','Place Required!','#msgDispl')) return false;
		if(!commonValidate('My_picode','','Pin Code Required!','#msgDispl')) return false;
		if(!commonValidate('My_districtid','','District Required!','#msgDispl')) return false;
		if(!commonValidate('My_mobNo','','Mobile Phone Number Required!','#msgDispl')) return false;
		/*if(!$('#My_mobNo').val().match('^(0|[1-9][0-9]*)$')){
			$("#msgDispl").html('Invalid Mobile Phone Number!');
			$("#My_mobNo").focus();
			return false;
		}*/
		if (!validateMobs("#My_mobNo","#msgDispl")) return false;
		if(!commonValidate('My_emailId','','Email Id Required!','#msgDispl')) return false;
		var emailID = document.getElementById("My_emailId").value; 	
		if (validateEmail(emailID) == false){
			$("#msgDispl").html('Invalid EmailId!');
			$("#My_emailId").focus();
			return false;
		}
}


//Display edit box for user Group

function editGroup_role(ids){
	var data_id     = '#row'+ids;
	var edit_id     = '#edt'+ids;
	if (($('#edt_hid').val() != ids) && $('#edt_hid').val()){ 
		var oldId     = $('#edt_hid').val();
		var o_data_id = "#row"+oldId;
	   	var o_edit_id = "#edt"+oldId;

	   	$(o_data_id).html($("#ch_group_role").val());
	   	var imgEdit = "<img src='../images/edit.gif' border=0 onClick='editGroup_role("+oldId+")'>";
	   	$(o_edit_id).html(imgEdit);
	}
	$(data_id).html("<input type='text' id='ch_group_role' name='ch_group_role' size='12px' value='"+$(data_id).html()+"'>");
	$(edit_id).html("<input type='submit' value='Update' name='update_New' class='button'>");	
        $('#edt_hid').val(ids);
}



//show Hide Functions
function showHideDisplay(btn_ids,dis_ids){
   
   if ($(btn_ids).val() == "Hide"){
	 $(btn_ids).val("Show");
	 $(dis_ids).hide();
   }
   else {
	 $(btn_ids).val("Hide");
	 $(dis_ids).show();
   }	
}

//Function to display product Details

function dataPostDisp(url,param,postn,nos){	
	var http = GetXmlHttpObject();
	http.open("POST", url, true);
	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", param.length);
	http.setRequestHeader("Connection", "close");

	http.onreadystatechange = function() {//Call a function when the state changes.
	   if(http.readyState == 4 && http.status == 200) {
		var resp      = http.responseText; 	
		if (!resp) alert("Invalid Serial Number!");
		else {
			$('#numberOfComl').val(nos);
			var dispId    = "#prodDet"+$("#numberOfComl").val(); 
			var prevNum   = parseInt($("#numberOfComl").val())-1;
			var curNo     = $("#numberOfComl").val();
			//var addMId    = "#addButtons"+prevNum; //alert("addMId="+addMId);
			var usrInf    = "#usrInf"+prevNum; //alert(usrInf);
			$(dispId).html(resp);
			//$(addMId).html("");
			$(usrInf).html("");
			//save all serial Numbers
			if ($("#allSerialNos").val())
				var allSlnosGet = $("#allSerialNos").val() +"::"+$(postn).val();
			else 	var allSlnosGet = $(postn).val(); //alert($(postn).val());
			$("#allSerialNos").val(allSlnosGet);
		}
		$("#loadImg").html("");
	   }
	   else {
		$("#loadImg").html("");//<img src='../images/load.gif' border=0>
	   }
	} 

	http.send(param);	
}




//Function to display product Details
function displayproductDetails(slId,nos){
	var url=paths+"Administrator/ajaxScript.php"; 
	var slno         = $(slId).val();
	var oldSlnos     = $("#allSerialNos").val();

	var oldSlnoSplit     = oldSlnos.split("::");
//	if(slno in oldSlnoSplit) alert("Exist");
//alert(oldSlnoSplit.length);
	var flgSlno = 0;
	for (i=0;i<oldSlnoSplit.length;i++) {
		if (oldSlnoSplit[i] == slno)  flgSlno = 1;		
	}
/*
	if (index = oldSlnoSplit.indexOf(slno)) alert("Exist!")
	else alert("Not Exist!");
*/

	if (flgSlno == 0) {
		var params = "oprn=prodDetail&vals="+slno+"&nos="+nos; //alert(params);
		dataPostDisp(url,params,slId,nos);
	} else alert("Serial Number already entered!");

}

//Function to display Add more serical Number
function addMorecomplaints(){
	var addMoreDispId = '#AddMore'+$("#numberOfComl").val();
//alert(addMoreDispId);
	var oldNo = $("#numberOfComl").val();
	var newNo =parseInt(oldNo)+1;
	var newSlId = 'prod_slno'+newNo;

//B4 Add more cpmplaints check whether filled previous one.  
	var falts     = '#faults'+oldNo;
	var oth_falts = '#oth_fault'+oldNo;
	
	if($(falts).val() || $(oth_falts).val()) {	
		var dispVal = "<br><div>Product Serial Number: <input type='text' name='"+newSlId+"' id='"+newSlId+"'> <input type='button' name='chkSerialNumber' value='Ok' class='button' onClick=\"displayproductDetails('#"+newSlId+"',"+newNo+")\"><div id='prodDet"+newNo+"'></div><br> <br>";
		$(addMoreDispId).html(dispVal)
	}
	else alert("Please select Faults!");
}	


//********** Make Validate *************

function validateMake() {
	if(!commonValidate('make_name','','Make Name Required!','#msgDis')) return false;
	if(!commonValidate('toll_fNo','','Toll Free Number Required!','#msgDis')) return false;
	if(!commonValidate('sec_email','','') && !commonValidate('prim_email','','Email-Id Required!','#msgDis'))return false;
	return confirm("Save?")? true:  false;
}

//********** Supplier Validate *************
function validateSupplier() {
	if(!commonValidate('supplr_name','','Supplier Name Required!','#msgDis')) return false;
	if(!commonValidate('toll_fNo','','Toll Free Number Required','#msgDis')) return false;
	if(!commonValidate('sec_email','','') && !commonValidate('prim_email','','Email-Id Required!','#msgDis'))return false;
	return confirm("Do you want to Save?")? true:  false;
}

//********** Service Provider Validate *************
function validateServiceProvider() {
	if(!commonValidate('sp_name','','Service Provider Name Required!','#msgDis')) return false;
	if(!commonValidate('toll_fNo','','Toll Free Number Required','#msgDis')) return false;
	if(!commonValidate('sec_email','','') && !commonValidate('prim_email','','Email-Id Required!','#msgDis'))return false;
	return confirm("Do you want to Save?")? true:  false;
}

//Validate Register Complaints
function validateRegistration(){
	var oldNo = $("#numberOfComl").val();
//B4 Add more cpmplaints check whether filled previous one.  
	var falts     = '#faults'+oldNo;
	var oth_falts = '#oth_fault'+oldNo;
	if($(falts).val() || $(oth_falts).val()) {
		   if(!commonValidate('contactName','','Contact Name Required!','#msgStatus')) return false;
	   if(!commonValidate('landNo','','Phone Number Required!','#msgStatus') && !commonValidate('mobNo','','Phone Number Required!','#msgStatus'))return false;
	   if(!commonValidate('email','','Email Required!','#msgStatus')) return false;
	   if (confirm("Do you want to Register the complaint(s)?")) return true;
	   else return false;
	}
	else {
		alert("Please select Faults!");
		return false;
	}
}


//display complaint Details based on the Keltron Id
function dispCompDetails(KelId,users,ids,grpId){

$("#ids"+ids).css("background-color","#ffecfd");
if ($("#hid_color").val()) {
     if (ids != $("#hid_color").val()){
	 var pids = "#ids"+$("#hid_color").val();	
	 $(pids).css("background-color","");
     }
}





$("#hid_color").val(ids);

	var url=paths+"Administrator/ajaxScript.php";
	var param = "oprn=compDetailDisp&kelId="+KelId+"&users="+users+"&groupId="+grpId; 

	var http = GetXmlHttpObject();
	http.open("POST", url, true);
	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", param.length);
	http.setRequestHeader("Connection", "close");

	http.onreadystatechange = function() {//Call a function when the state changes.
	   if(http.readyState == 4 && http.status == 200) {
		var resp      = http.responseText; 					
		$("#comp_details").html(resp);
	   }
	   else {
		$("#loadImg").html("");//<img src='../images/load.gif' border=0>
	   }
	} 

	http.send(param);
}


//dispute Entry Details





//Pop Up align view
jQuery.fn.center = function () {
   this.css("position","absolute");
   this.css("top", ( $(window).height() - this.height() ) -40 +$(window).scrollTop() + "px");
   this.css("left", ( $(window).width() - this.width() ) /3+$(window).scrollLeft() + "px");
   return this;
}

jQuery.fn.top = function () {
   this.css("position","absolute");
   this.css("top", ( $(window).height() - this.height() ) -300 +$(window).scrollTop() + "px");
   this.css("right", ( $(window).width() - this.width() ) /15+$(window).scrollLeft() + "px");
   return this;
}



var popStatus = 0;
function hidePopup()
{
   if (popStatus == 1){
	
	$("#bg_table").fadeOut("slow");
	$("#popupDiv").fadeOut("slow");
	popStatus = 0;
   }

}

function complaintIdPopup(compId,emails){ 


	if ( popStatus == 0) {
		$("#popupDiv").center();
		$("#bg_table").css({ "opacity": "0.7"
        	});
	
		$("#bg_table").fadeIn("slow");
		$("#popupDiv").fadeIn("slow");
		popStatus = 1;
	}
	var url=paths+"Administrator/ajaxScript.php";
	var param = "oprn=CallTicketEntry&compId="+compId+"&emails="+emails; //alert(param);
	var http = GetXmlHttpObject();
	http.open("POST", url, true);
	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", param.length);
	http.setRequestHeader("Connection", "close");

	http.onreadystatechange = function() {//Call a function when the state changes.

	   if(http.readyState == 4 && http.status == 200) { 
	        $("#popupDiv").html("");
		var resp      = http.responseText; 	
		$("#popupDiv").html(resp);
	   }	  
	} 
	http.send(param);
}



function complaintStatusPopupTest(pend,reass,callreg,part){ 	
	if ( popStatus == 0) {
		$("#popupDiv").top();		
		$("#popupDiv").fadeIn("slow");
		popStatus = 1;
	}
	
	var url=paths+"Administrator/ajaxScript.php";
	//alert(url);
	var param = "oprn=CallStatus&pend="+pend+"&reass="+reass+"&callreg="+callreg+"&part="+part; //alert(param);
	var http = GetXmlHttpObject();	
	http.open("POST", url, true);
	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", param.length);
	http.setRequestHeader("Connection", "close");

	http.onreadystatechange = function() {//Call a function when the state changes.
	   if(http.readyState == 4 && http.status == 200) { 	       
	        $("#popupDiv").html("");
		var resp      = http.responseText; 	
		$("#popupDiv").html(resp);
	   }	  
	} 
	http.send(param);
}

function complaintStatusPopupTestDel(res,clos){ 	
	if ( popStatus == 0) {
		$("#popupDiv").top();		
		$("#popupDiv").fadeIn("slow");
		popStatus = 1;
	}
	
	var url=paths+"Administrator/ajaxScript.php";
	//alert(url);
	var param = "oprn=CallStatusDel&res="+res+"&clos="+clos; //alert(param);
	var http = GetXmlHttpObject();	
	http.open("POST", url, true);
	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", param.length);
	http.setRequestHeader("Connection", "close");

	http.onreadystatechange = function() {//Call a function when the state changes.
	   if(http.readyState == 4 && http.status == 200) { 	       
	        $("#popupDiv").html("");
		var resp      = http.responseText; 	
		$("#popupDiv").html(resp);
	   }	  
	} 
	http.send(param);
}


function callticketAssign(compType){
	if (compType != 1) {
		$('#compIdDisp').hide();
		$('#assign_calltkt').val('Post');
	}	
	else 
	{
		$('#compIdDisp').show();
		$('#assign_calltkt').val('Assign');
	}
}

//Function validate CallTicket Post
function validateCalltktAssign(){
	if ($('#compType').val() == 1) {
	        if(!commonValidate('calltktId','','Complaint Id Required!','#msgDisp')) return false;
	} 
        if(!commonValidate('calltkt_remark','','Remarks Required!','#msgDisp')) return false;
}


function disputeEntry(complId){ 
//For pop up view

	if ( popStatus == 0) {
		$("#popupDiv").center();
		$("#bg_table").css({ "opacity": "0.7"
        	});
	
		$("#bg_table").fadeIn("slow");
		$("#popupDiv").fadeIn("slow");
		popStatus = 1;
	}

	var url=paths+"Administrator/ajaxScript.php";
	var param = "oprn=disputeDisp&compId="+complId; 
	var http = GetXmlHttpObject();
	http.open("POST", url, true);
	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", param.length);
	http.setRequestHeader("Connection", "close");

	http.onreadystatechange = function() {//Call a function when the state changes.
	   if(http.readyState == 4 && http.status == 200) {
	        $("#popupDiv").html("");
		var resp      = http.responseText; 	
		//$("#disputeEntyDisp").show();
		$("#popupDiv").html(resp);
	   }	  
	} 

	http.send(param);	
}

/*
var popupStatus = 0;

//loading popup with jQuery magic!
function loadPopup(){
       //loads popup only if it is disabled
       if(popupStatus==0){
               $("#backgroundPopup").css({
                       "opacity": "0.7"
               });
               $("#backgroundPopup").fadeIn("slow");
               $("#popupContact").fadeIn("slow");
               popupStatus = 1;
       }
}
 
*/










//Complaint Status Update
function viewProductDet(disp,the){
	$("#dispParts").hide();
	$("#dispProd").hide();

	$("#partsName :selected").attr('selected', '');
 

	$("#modelNo").val("");
	$("#serialNo").val("");

	if (disp != "") {
		if (the.checked == true)	$(disp).show();
		else 		$(disp).hide();
	}
}

//Complaint Status Update
function viewProductServiceDet(disp,the){
	
	$("#dispServiceParts").hide();

	$("#service_partsName :selected").attr('selected', '');

	$("#service_modelNo").val("");
	$("#service_serialNo").val("");

	if (disp != "") {
		if (the.checked == true)	$(disp).show();
		else 		$(disp).hide();
	}
}


//Validate School Information
function validateSchoolInfo(){
        if(!commonValidate('district_id','','District Required!','#msgDisplay')) return false;
        if(!commonValidate('school_typ_id','','School Type Required!','#msgDisplay')) return false;
        if(!commonValidate('school_code','','School Code Required!','#msgDisplay')) return false;
        if(!commonValidate('school_name','','School Name Required!','#msgDisplay')) return false;
        if(!commonValidate('address1','','Address Required!','#msgDisplay')) return false;
        if(!commonValidate('place','','Place Required!','#msgDisplay')) return false;
        if(!commonValidate('pincode','','Pincode Required!','#msgDisplay')) return false;
	if(!$('#pincode').val().match('^(0|[1-9][0-9]*)$')){
			$("#msgDisplay").html('Invalid Pincode!');
			$("#pincode").focus();
			return false;
	}

	if ($("#hm_mob").val()!="") {
		if (!validateMobs("#hm_mob","#msgDisplay")) return false;
	}

	if ($("#itinch_mob").val()!="") {
		if (!validateMobs("#itinch_mob","#msgDisplay")) return false;
	}

	if (confirm("Do you want to Save the School Information?")) return true;
	else return false;	
}

//Validate FAQ
function validatefaq(){
        if(!commonValidate('faq','','Post your question!','#msgDisplay')) return false;
	if (confirm("Do you want to Post?")) return true;
	else return false;
}

//validate Registration details
function validateCompStatus(admnType,prevDt,postDt){ 

        if(!commonValidate('txt_hr','','Hours Required!','#msgDisplay')) return false;

	var fromTmHH = $("#txt_hr").val();
	var fromTmMM = $("#txt_min").val();

	if (fromTmHH > 12 || fromTmMM>60) {
		$("#msgDisplay").html("Invalid Time!");
		return false;	
	}


	var fromDate = $("#status_date").val();
	frmdtSplt = fromDate.split("-");
/*
	var fromTmHH = $("#txt_hr").val();
	var fromTmMM = $("#txt_min").val();

	if ($("#time_set").val() == 'pm')		fromTmHH = (fromTmHH  % 12) + 12;

	var frmDtTime = frmdtSplt[2]+"-"+frmdtSplt[1]+"-"+frmdtSplt[0]+" "+fromTmHH+":"+fromTmMM+":00";
*/
	var startDate = new Date(frmdtSplt[2],(frmdtSplt[1]-1),frmdtSplt[0],0,0,0);


	var prevDtExp   = prevDt.split(" ");	
	var prevDateExp = prevDtExp[0].split("-");

	// Split current time
	var postDtExp   = postDt.split(" ");
	var postDateExp = postDtExp[0].split("-");


	// Post time Stamp for comparison
	var prevTimeStamp = new Date(prevDateExp[0],(prevDateExp[1]-1),prevDateExp[2],0,0,0);
	var postDate      = new Date(postDateExp[0],(postDateExp[1]-1),postDateExp[2],0,0,0);
 
 	// Compare post date with the entered date
	if (postDate > startDate) { 
			$("#msgDisplay").html("Please select a date after complaint posted date!");
			return false;
	} 

	if (prevTimeStamp > startDate) { 
		$("#msgDisplay").html("Only one preceding working day can be selected. ");
		return false;
	}

 

        if(!commonValidate('comp_status','','Status Required!','#msgDisplay')) return false;
        if(!commonValidate('remark','','Action Taken Required!','#msgDisplay')) return false;
	
	var replacedItem_val = $('input:radio[name=replace_item]:checked').val();

	if ($("#comp_status").val() == 6){
  	   if (replacedItem_val == 'Product') {

		if ($("#cmbModelNo").val() == "Other" && $("#modelNo").val() == "")	{
			$("#msgDisplay").html("Model Number Required!");
			return false;
		}

		if ($("#serialNo").val() == "")	{
			$("#msgDisplay").html("Serial Number Required!");
			return false;
		}
	   }
	}
	if (confirm("Do you want to update Status?")){
		return true;
	} else return false;

}

//Change Password Validate
function validateChangePassword(){
        if(!commonValidate('curPw','','Current Password Required!','#msgDisplay')) return false;
        if(!commonValidate('newPw','','New Password Required!','#msgDisplay')) return false;
        if(!commonValidate('confirmPw','','Confirm Password Required!','#msgDisplay')) return false;
	if ($("#newPw").val() != $("#confirmPw").val()) { 
	   	$("#msgDisplay").html('Invalid Confirm Password!');  
		$("#confirmPw").focus();  
		return false;
	}
	if (confirm("Do you want to change the password?")) return true;
	else return false;
}



//Function for forgot Password Popup
function getForgotpw(){
	if ( popStatus == 0) {
		$("#popupDiv").center();
		$("#bg_table").css({ "opacity": "0.7"
        	});
	
		$("#bg_table").fadeIn("slow");
		$("#popupDiv").fadeIn("slow");
		popStatus = 1;
	}
}


//Validate Forgot Password
function validateForgotpw(){
        if(!commonValidate('forgot_userName','','User Name Required!','#msg_status')) return false;
        if(!commonValidate('forgot_email','','Email Id Required!','#msg_status')) return false;	
}

//Validate Contact Us 

function validatecontactUS(){       
        if(!commonValidate('contact_name','','Name Required!','#msg_status')) return false;
        if(!commonValidate('contact_Email','','Email Id Required!','#msg_status')) return false;
        if(!commonValidate('contact_PhNo','','Eontact Number Required!','#msg_status')) return false;
        if(!commonValidate('contact_sub','','Subject Required!','#msg_status')) return false;
        if(!commonValidate('contact_msg','','Message Required!','#msg_status')) return false;
}

//FAQ More List View
function moreList(lmt,totrec){
	var preVal = $("#hid_moreList").val();
	if (preVal == "") preVal = lmt;

	var newLmt = parseInt(preVal)+parseInt(lmt); 
	if (totrec > preVal) {
		$("#hid_moreList").val(newLmt);
		document.faqGen.submit();
	}
}
//		  
function dispComUpdatedetails(){
   $("#compStatus_Details").show();
   $("#comStatBtn").hide();
   $("#compStatusDisp").hide();
}

//Dict make /Supplier details
function editMakeSuplr(mkID) {
	var mkNme   = "#mk_nm"+mkID;
	var tolFr   = "#tol_fre"+mkID;
	var primEm  = "#pr_email"+mkID;
	var secEm   = "#sec_email"+mkID;
	var idImg   = "#id_img"+mkID;

	if (($('#edt_hid').val() != mkID) && $('#edt_hid').val()){ 
	   var oldMId = $('#edt_hid').val();
	   var o_mkNme   = "#mk_nm"+oldMId;
	   var o_tolFr   = "#tol_fre"+oldMId;
	   var o_primEm  = "#pr_email"+oldMId;
	   var o_secEm   = "#sec_email"+oldMId;
	   var o_idImg   = "#id_img"+oldMId;

//	   $(mkNme).html($(mkNme).val());
	   $(o_mkNme).html($("#ch_newName").val());
	   $(o_tolFr).html($("#ch_tolfre").val());
	   $(o_primEm).html($("#ch_pemail").val());
	   $(o_secEm).html($("#ch_secemail").val());

	   var imgEdit = "<img src='../images/edit.gif' border=0 onClick='editMakeSuplr("+oldMId+")'>";
	   $(o_idImg).html(imgEdit);
	}

	   $(mkNme).html("<input type='text' id='ch_newName' name='cha_newName' size='12px' value='"+$(mkNme).html()+"'>");
	   $(tolFr).html("<input type='text' id='ch_tolfre' name='ch_tolfre' size='15px' value='"+$(tolFr).html()+"'>");
	   $(primEm).html("<input type='text' id='ch_pemail' name='ch_pemail' size='20px' value='"+$(primEm).html()+"'>");
	   $(secEm).html("<input type='text' id='ch_secemail' name='ch_secemail' size='12px' value='"+$(secEm).html()+"'>");
	   $(idImg).html("<input type='submit' value='Update' name='update_New' class='button'>");
	
	   $('#edt_hid').val(mkID);
}

//Admin USer Delete
function deleteUser(tabFld,uid) {//alert("sss");
   if (confirm("Do you want to delete?")){
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	{
		alert ("Browser does not support HTTP Request");
		return;
	}
	var url=paths+"Administrator/ajaxScript.php";
	url=url+"?tabField="+tabFld+"&val_id="+uid+"&oprn=delUser";	
	xmlHttp.onreadystatechange=userDelete;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
   }
}



function userDelete() 
{ 

	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { 
		$("#loadImg").html("");
		alert(xmlHttp.responseText);
		var sURL = unescape(window.location.pathname);
		window.location.href = sURL;
 	} 
	else {
		$("#loadImg").html("");//<img src='"+paths+"images/load.gif' border=0>
	}
}

function showRoles(str,school_code){
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	{
		alert ("Browser does not support HTTP Request");
		return;
	}

	if (school_code!="") { 
		if (str == '1') {
			var scholDet = "<td>School Code</td> <td><input type='text' name='schoolCd' id='schoolCd'></td><td>School Name</td> <td><input type='text' name='schoolName' id='schoolName'></td>";
			$(school_code).html(scholDet);
		} else {
			$(school_code).html("");
		}
	
		//document.getElementById(school_code).style.display=inline;
	}
	var url=paths+"Administrator/ajaxScript.php";
	url=url+"?group_id="+str+"&oprn=roleDisp";
	
	xmlHttp.onreadystatechange=stateChange;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function stateChange() 
{ 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{ 
		//$("#loadImg").html("");
		$("#roleDisplay").html(xmlHttp.responseText);
		//document.getElementById("roleDisplay").innerHTML=xmlHttp.responseText;
 	} 
	else {
		//$("#loadImg").html("<img src='"+paths+"images/load.gif' border=0>");
	}
}


//Holiday setting
function editHolidayDetails(ids){
	var reason_id   = '#reason'+ids;
	var dt_id       = '#dts'+ids;
	var edit_id     = '#edt'+ids;

	if (($('#edt_hid').val() != ids) && $('#edt_hid').val()){ 
		var oldId     = $('#edt_hid').val();
		var o_reason_id   = '#reason'+oldId;
		var o_dt_id       = '#dts'+oldId;
		var o_edit_id     = '#edt'+oldId;

	   	$(o_reason_id).html($("#ch_reason").val());
	   	$(o_dt_id).html($("#ch_dt").val());

	   	var imgEdit = "<img src='../images/edit.gif' border=0 onClick='editHolidayDetails("+oldId+")'>";
	   	$(o_edit_id).html(imgEdit);
	}
	$(reason_id).html("<input type='text' id='ch_reason' name='ch_reason'  value='"+$(reason_id).html()+"'>");
	$(dt_id).html("<input type='text' id='ch_dt' name='ch_dt' size='12px' value='"+$(dt_id).html()+"'>");
	$(edit_id).html("<input type='submit' value='Update' name='update_New' class='button'>");	
        $('#edt_hid').val(ids);
}
//FAQ edit Details
function editFaq(faqID) {
	var qnId     = "#qnId"+faqID;
	var edtImgId = "#edtImgId"+faqID;

	if (($('#edt_hid').val() != faqID) && $('#edt_hid').val()){ 
	   var oldId      = $('#edt_hid').val();
	   var o_qnId     = "#qnId"+oldId;
	   var o_edtImgId = "#edtImgId"+oldId;

	   $(o_qnId).html($("#ch_qstn").val());

	   var imgEdit = "<img src='../images/edit.gif' border=0 onClick='editFaq("+oldId+")'>";
	   $(o_edtImgId).html(imgEdit);
	}

	   $(qnId).html("<input type='text' id='ch_qstn' name='ch_qstn' size='50px' value='"+$(qnId).html()+"'>");
	   $(edtImgId).html("<input type='submit' value='Update' name='update_New' class='button'>");
	   $('#edt_hid').val(faqID);
}

//FAQ Display Ans Box
function displayFaqAns(faqId){
	var oldAnsId = $("#ans_edt_hid").val();
	if (oldAnsId != "") {
		O_ansId    = '#AnsId'+oldAnsId;
		var oldAns = $("#faq_Ans").val();
		$(O_ansId).html(oldAns);

	}
	ansId    = '#AnsId'+faqId;
	var FaqAns = $(ansId).html();
	var DispContent = "<input type='text' name='faq_Ans' id='faq_Ans' size='50px' value='"+FaqAns+"'> <input type='submit' name='save_faqAns' value='Save' class='button'>";	
	$("#ans_edt_hid").val(faqId);
	$(ansId).html(DispContent);	
}

//Update MyAccount Details
function updateMe(flg){ 
	if (flg == 'U') {
	 	$("#updateMyAcc").show();
	 	$("#viewMyAcc").hide();
	} else {
	 	$("#updateMyAcc").hide();
	 	$("#viewMyAcc").show();
	}
}

//Product Parts Details
function parts_check()   {
  		if(!commonValidate('cmbProductPart','','Please Select Product Name!','#msg_Name')) return false;
		if(!commonValidate('txtProductPart','','Please Enter Product Parts!','#msg_Name')) return false;
}
function parts_search_check()   {
   		if(!commonValidate('cmbProductPartSearch','','Please Select Product Type!','#msg_Name')) return false;			
   }


//Pagination Script

function sbtForm(page,val,totalrec,rlimit,balRows,frmId)
{	
	var recno=parseInt(document.getElementById("txtEntVal").value);
	var nxtrecno=parseInt(recno)+parseInt(rlimit);
	if(!totalrec) return false
	else if(val=="last" || val=="next")
	{
		if(parseInt(recno)>parseInt(totalrec))
		{	
			alert("There are only "+totalrec+" Records")

			return false
		}
		else if(val=="next" )//|| val=="last"
		{
				if(parseInt(nxtrecno)>parseInt(totalrec))
				{
					alert("There are only "+totalrec+" Records")
					return false;
				}
					document.getElementById(frmId).action=page+"?gloSel="+val
					document.getElementById(frmId).submit()
		}
		else
		{
			document.getElementById(frmId).action=page+"?gloSel="+val
			document.getElementById(frmId).submit()
		}
	}
	else
	{ 
		document.getElementById(frmId).action=page+"?gloSel="+val
		document.getElementById(frmId).submit()
	}
}



function detaildComplaintPopup(typeId,districtId,compType,idCell){ 

$(".idpopClass").css("background-color","");
$("#"+idCell).css("background-color","#e0c9c5");

	if ( popStatus == 0) {
		$("#popupDiv").center();
		$("#bg_table").css({ "opacity": "0.7"
        	});
	
		$("#bg_table").fadeIn("slow");
		$("#popupDiv").fadeIn("slow");
		popStatus = 1;
	}
	var url=paths+"Administrator/compliant_ajaxScript.php";
	var param = "actions=detaildComplaintPopup&getTypeId="+typeId+"&getDistrictId="+districtId+"&getCompType="+compType; 
	//alert(param);
	var http = GetXmlHttpObject();
	http.open("POST", url, true);
	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", param.length);
	http.setRequestHeader("Connection", "close");

	http.onreadystatechange = function() {//Call a function when the state changes.

	   if(http.readyState == 4 && http.status == 200) { 
	        $("#popupDiv").html("");
		var resp      = http.responseText; 	
		$("#popupDiv").html(resp);
	   }	  
	} 
	http.send(param);
}

