var curZoneType;
$(document).ready(function(){
	curZoneType	=	$('input[name=deliveryZoneType]:checked').val();
	if($('#selectedCountries').val()){		
                 $("#ajax_new_countryDiv").show();
                 tableHeadToggle();
                 if(curZoneType=='National'){
                     setCountry($('#selectedCountries').val());
                 }
	}			
designChanges(curZoneType);	
$('input[name=deliveryZoneType]').click(function()
{
  var zonetype=$('input[name=deliveryZoneType]:checked').val()
	
	if($('input[name=deliveryZoneType]:checked').val()!=curZoneType)
	{
             $('#cityLoc_loader').removeClass("hide");
             $('#addNewCountry').hide();
             setCountry(0);
		if($('#countryCount').val()>0)
		{
			jConfirm(lblCountryAlongState, deleteText, function(r) {
    		if (r)
			{
                            designChanges(zonetype); 
                                $('#ajax_new_countryDiv').hide();                                 		
                                 var selectedCountries         = $('#selectedCountries').val();
				selCountries_array=selectedCountries.split(',');
				for(i=0;i<selCountries_array.length;i++)
				{
					if(selCountries_array[i]!=0)
					{
						$('#AjaxCountryExists_'+selCountries_array[i]).remove();
						selectAllState('state','','',selCountries_array[i]);
					}
				}                               	
                                  
				$('#countryCount').val(0);
				$('#selectedCountries').val(0);
                                                                 
			}
			else
			{
				$('input[name=deliveryZoneType]').prop('checked',false);
				$('input:radio[value='+curZoneType+']').prop('checked',true);
				var labelFor	=	$('input[name=deliveryZoneType]:checked').attr('id');
				$('label[for^=deliveryZoneType]').removeClass('checked');
				$('label[for='+labelFor+']').attr('class','checked');
                                $('#cityLoc_loader').addClass("hide");
                                $('#addNewCountry').show();
			}
			curZoneType	=	$('input[name=deliveryZoneType]:checked').val();
			});
		}else {
		curZoneType	=	$('input[name=deliveryZoneType]:checked').val();       
                
                designChanges(curZoneType);   
                }
                            
	}
});

$(document).on('submit','#formDeliveryZone',function(){   
        var zoneType	=	$('input:radio[name=deliveryZoneType]:checked').val();//&& $('#deliveryZoneDescription').val()!='' 
	
    if($('#deliveryZoneName').val()!='' && ($('#selectedCountries').val()=='' || $('#selectedCountries').val()==0)) {
		jAlert(lblSelectOneCountry);
	    return false;
	}	
        nameExists($('#deliveryZoneName').val());          
		 var curr_form_errors = $('#formDeliveryZone_errors').val();
		 if(curr_form_errors==0) {
			 if($("#selectedCountries").val()=='' || $("#selectedCountries").val()==0){
				 jAlert(lblPleaseAddCountry);
				 return false;
			 } else if (zoneType!='National'){
				 var selectedCountries         = $('#selectedCountries').val();
				  selCountries_array=selectedCountries.split(',');
				   for(i=0;i<selCountries_array.length;i++){
					if(selCountries_array[i]!=0){
					 if($(".statearray_"+selCountries_array[i]+":checked").size()==0){
									  var countryName=$('#hidCountryName_'+selCountries_array[i]).val();
									  if(countryName!=''){
										  jAlert(msgAddState+'"'+countryName+'"');
										  return false;
									  }else{
                                                                              return true;
                                                                          }
							   }
						   }
					  }
			  }
		   } 		
    
});

$(document).on('change',"#AddCountry",function(){
            $('.div-city').hide();   
            $('#addNewCountry').html('<span class=plus-v></span><span class=plus-h></span>'+lblAdd);
            if ($(this).val()>0) {
            listStates($(this).val());
            }else {
                $("#stateInput").html('');		
            }
        }); 
 $(document).on('click',"#AjaxShowStatesDiv",function(){
             $('.div-city').slideToggle("slow");
	     $(this).find(".arw-icon").toggleClass("arw-top");
        });   

 $(document).on("change",'#deliveryZoneName',function(){
     nameExists($(this).val());       
 });
});
function nameExists(name)
{
    var deliveryZoneID = $('#deliveryZoneID').val();  
       dataArray			= new Array();
       dataArray[0] 			= deliveryZoneID;   
        dataArray[1] 			= name;
        if($.trim(name)!='') {  
	   $.ajax({
				   	type: "POST",
                                        async:false,
					url: GLOBAL_BASE_PATH+"/deliveryzone/ajaxExists/",		      		
		           	data: { ajax_request: dataArray},
				   	success: function(msg){ 
					if(msg=='1')
					{
                                          $('#countExists').val(1);                                         
                                          $('#div_err_formDeliveryZone_validateState').removeClass("hide"); 
                                         // alert(errDeliveryZoneAlreadyExist)
                                        }else {
                                            $('#countExists').val(0);
                                        }                                        	
				}
	   });
        }else {             
           $('#countExists').val(0);
        }       
         $("#countExists").trigger('blur');
         $("#validateState").trigger('change');        
}
function selectAllState(B,A,check,countryID){    
	
        if(check.checked){
            $('#SelectAll_'+countryID).attr('title',lblDeselectAll);
            $("li[id^='left_"+B+countryID+"_']").find("input").prop('checked',true);}
        else {
            $('#SelectAll_'+countryID).attr('title',lblSelectAll);	
            $("li[id^='left_"+B+countryID+"_']").find("input").prop('checked',false);}
	
};

function checkselectAll(countryID)
{
	var total_checkboxes=$(".stateCheckbox_"+countryID+" ").size();
	var checked=$(".stateCheckbox_"+countryID+" :checked").size();
	if(total_checkboxes==checked){		
		$('#SelectAll_'+countryID).attr('title',lblDeselectAll);		
		$('#SelectAll_'+countryID).find("input").prop('checked',true);
	} else {
		$('#SelectAll_'+countryID).attr('title',lblSelectAll);	
                $('#SelectAll_'+countryID).find("input").prop('checked',false);
	}
    // if(checked==0) $('#ajax_new_countryDiv').hide();
};
function checkselectAddedAll(countryID)
{
	var checked=$(".statearray_"+countryID+":checked").size();	
        if(checked==0) {
            $('#AjaxCountryExists_'+countryID).remove();
            setCountry(0);
            var selectedCountries=$('#selectedCountries').val();
			selCountries_array=selectedCountries.split(',');
			countryCount	=	$('#countryCount').val();
			countryCount	=	countryCount-1;
			$('#countryCount').val(countryCount);
			var res_country_list=0;
			for(i=0;i<selCountries_array.length;i++){
				if(selCountries_array[i]!=countryID && selCountries_array[i]!=0){
					 res_country_list=res_country_list+','+selCountries_array[i];
				}
			}
                       
			$('#selectedCountries').val(res_country_list);
                         if(res_country_list=='0'){
                            $('#ajax_new_countryDiv').hide();
                        }
                        
    }
};
function delStateAjax(countryID,stateID,zip,th){
    jConfirm(errStateDeleteConfirm, 'Delete', function(r) {
        if (r){           
            if(typeof(zip)  !== "undefined") {
               $(th).parent().parent().remove();
            }
            if(zip==''){
                $('#check_'+stateID).prop('checked',false);
                $("li[id^='left_state"+countryID+"_']").find('#check_'+stateID).prop('checked',false);
               } 
               if($("#states_list_"+countryID+" > tbody > tr").length==0){

               checkselectAddedAll(countryID);
               checkselectAll(countryID);
               } 
                return false;
            
    }if (!r)	
			
			return false;	
 	 });    

}
function listStates(country_id,editedState,row,th){

	dataArray			= new Array();
        zoneType	=	$('input:radio[name=deliveryZoneType]:checked').val();
        deliveryZoneID = $('#deliveryZoneID').val();  
        if(zoneType!='National'){
            $('#addNewCountry').hide();
	 if(country_id!=''){   
           var  slctdStates    =   '';
           $(".statearray_"+country_id+":checked").each(function(){
               slctdStates=slctdStates+','+$(this).val();    
           });
	   $('#cityLoc_loader').removeClass("hide");
	   dataArray[0] 			= country_id;	 
	   dataArray[1] 			= zoneType;
           dataArray[2] 			= deliveryZoneID;
           dataArray[3] 			= editedState;
           dataArray[4] 			= row;
	   $.ajax({
				   	type: "POST",
					url: GLOBAL_BASE_PATH+"/deliveryzone/ajaxState/",		      		
		           	data: { ajax_request: dataArray,slctdStates:slctdStates },
				   	success: function(msg){ 
					if(msg!='1')
					{					
                                                $('#cityLoc_loader').addClass("hide");
				   	 	$("#stateInput").html(msg);						
                                                $('.div-city').hide();
                                                if(zoneType=='Location' && row=='zip')  // EDIT LOCATION ZIp
                                                {
                                                    $('#editZipAction').val(row);
                                                    $('#isRange').val($(th).parent().parent().find('#isRange'+country_id+"_"+editedState).val());
                                                    showRange($("#isRange").val())  ;
                                                    if($("#isRange").val()=='Yes'){
                                                        var currZipCode = $(th).parent().parent().find('#zipCodes'+country_id+"_"+editedState).val().split(' - ');
                                                        $('#rangeFrom').val(currZipCode[0]);
                                                        $('#rangeTo').val(currZipCode[1]);
                                                    } else {
                                                        $("#zipCode").val($(th).parent().parent().find('#zipCodes'+country_id+"_"+editedState).val());
                                                    }
                                                    
                                                }


				    }
                                    $('#addNewCountry').show();
				}
	   });
	 } else {
              jAlert(errSelectCountry);
         }
        } 
}

function addCountryState()
{
	countryCount	=	$('#countryCount').val();
	countryCount	=	parseInt(countryCount)+1;
	dataArray			= new Array();
	var country_id         = $('#AddCountry').val();
         if(country_id==''){
             jAlert(errSelectCountry);
             return false;
         }
	var zoneType	=	$('input:radio[name=deliveryZoneType]:checked').val();
	var selectedCountries         =0;
        if($('#selectedCountries').val()){
	 	selectedCountries         = $('#selectedCountries').val();
	 } 
	 if(country_id){
		 selectedCountries		=	selectedCountries+','+country_id;
	 }
          var selectedstates =  '0';
          var slctdStatsLoctn='0';
	 
       if(zoneType=='Region'){
           $('.stateCheckbox_'+country_id+' input:checkbox:checked').each(function(){
                selectedstates		=	selectedstates+','+$(this).val();              
           });
          var stateselectedCount =    $('.stateCheckbox_'+country_id+' input:checkbox:checked').size();
          if(stateselectedCount==0  && $('#AjaxAllStates_'+country_id).val()=='0'){
              jAlert(msgAddState + $('#AddCountry').find("option:selected").text());
              return false;
          }
       } else if(zoneType=='Location'){
           selectedstates		=	$('#stateFrLocation_'+country_id).val(); 
           slctdStatsLoctn              =       slctdStatsLoctn+','+selectedstates;   
           $('#slctdStatsLoctn').val(slctdStatsLoctn);     
            if($('#stateFrLocation_'+country_id).val()==''){
              jAlert(msgAddState + $('#AddCountry').find("option:selected").text());
              return false;
          } 
          if($.trim($('#isRange').val())=='Yes'){

                if(($.trim($('#rangeFrom').val())=='') || ($.trim($('#rangeTo').val())=='')  ){
                    jAlert(errRange );
                    return false;
                }
                if(parseInt($('#rangeFrom').val())>parseInt($('#rangeTo').val())){
                      jAlert(errValidZIPRange);
                    return false;
                }
          }else{
           if($.trim($('#zipCode').val())=='' || $.trim($('#zipCode').val())=='*'){

               $('#zipCode').val('');
              jAlert(errZIP);
              return false;
          }
          }
       }       
        $('#addNewCountry').hide();
     if(country_id!=''){
	   $('#cityLoc_loader').removeClass("hide");
	   dataArray[0] 			= country_id;	  
	   dataArray[1] 			= zoneType;
            dataArray[2] 			= selectedstates;


            if(zoneType=='Location'){
                if($.trim($('#isRange').val())=='Yes'){
                    dataArray[3] 			= $.trim($('#rangeFrom').val()) + " - "+$.trim($('#rangeTo').val());//.replace(/[ ]+/g, ", ").replace(/\r?\n/g, ', '); 
                } else {
                    dataArray[3] 			= $('#zipCode').val().replace(/\s/g, "") ;  
                }
                dataArray[4] 			= slctdStatsLoctn; 
                dataArray[5] 			= $.trim($('#isRange').val()); 
            }
	   $.ajax({
				   	type: "POST",
					url: GLOBAL_BASE_PATH+"/deliveryzone/ajax/",		      		

                                        data: { ajax_request: dataArray,selids: selectedCountries },
				   	success: function(msg){ 
					if(msg!='1')
					{
						tableHeadToggle();
                                                $('#cityLoc_loader').addClass("hide");
                                                $("#ajax_new_countryDiv").show();
                                                resarray=msg.split('~*');
                                                if(zoneType=='Location'){                                                                                                            
                                                            if(resarray[0]=='1'){
                                                                var stateLoc    =   '0';
                                                                if($('#stateFrLocation_'+country_id).length >0){
                                                                     stateLoc    =   $('#stateFrLocation_'+country_id).val();                                                                   
                                                                }   
                                                                if($('#editZipAction').val()=='zip') 
                                                                { //state exists                                                               
                                                                  $("#right_state"+country_id+"_" + stateLoc+"_"+$('#editZipAction').val()).replaceWith(resarray[1]); 
                                                                  $('#editZipAction').val('');
                                                                  $('#addNewCountry').html('<span class=plus-v></span><span class=plus-h></span>'+lblAdd);
                                                                }  
                                                                else  
                                                                {
                                                                    $('#states_list_'+country_id).find('tbody').append(resarray[1]);    
                                                                }
                                                             //country not exists    
                                                            } else{
                                                                $("#ajax_new_country").append(resarray[1]);  
                                                            } 
                                                            //empty zipcode
                                                            $("#zipCode,#rangeFrom,#rangeTo").val('');
                                                    }else{

                                                        if(resarray[0]=='1'){
                                                            $("#AjaxCountryExists_"+country_id).remove();
                                                        } 
                                                        $("#ajax_new_country").append(resarray[1]);                                                        
                                                        $('.div-city').slideToggle("slow");
                                                        //set country if no states
                                                       if($('#AjaxAllStates_'+country_id).val()=='1'){setCountry(0);}
                                                       if(zoneType=='National')
                                                       {
                                                            $("#AddCountry option[value='"+country_id+"']").remove();
                                                       }
                                                    }                                                    
                                                     $('#countryCount').val(countryCount);
                                                $("#div_err_formDeliveryZone_countryCount").addClass('hide');     
                                        }
                                        $('#selectedCountries').val(selectedCountries);
                                        $('#addNewCountry').show();
                                         setCountry(0);
				}
	   });
	} else {
		jAlert(errSelectCountry);
                 $('#addNewCountry').show();

	}

}			 

function delCountry(country_id)
{
	var state_checked = [];
	$(".statearray_"+country_id).each(function(index) {
		if($(this).prop('checked')==true){
			state_checked.push($(this).val());
		}
	});
        var nowSelectCntry  =   $("#AddCountry").val();

	jConfirm(lblCountryAlongState, 'Delete', function(r) {
            if (r){
			$('#AjaxCountryExists_'+country_id).remove();			
                        $("#AddCountry").val(nowSelectCntry);                        
                        checkselectAll(country_id);
                        checkselectAddedAll(country_id);			
            }
            if (!r)	
                    for(i=0;i<state_checked.length;i++){			
                            $('#check_'+state_checked[i]).prop('checked',true);
                    }
            return false;	
        });    
}

function setCountry(country_list)
{
	 dataArray			= new Array();
	 dataArray[0] 			= country_list;
	 $.ajax({
				type: "POST",
				url: GLOBAL_BASE_PATH+"/deliveryzone/ajaxSetCountry/",
				data: { ajax_request: dataArray },
				success: function(msg){
					$("#AddCountry").html(msg);
                                        $("#stateInput").html('');
                                        $('#cityLoc_loader').addClass("hide");
                                        $('#addNewCountry').show();
				}
	});
}
function showZipDiv(){


    $("#liZipCodes").show();
        $("#zipCode").val(''); 
        $("#editZipAction").val(''); 
        $('#addNewCountry').html('<span class=plus-v></span><span class=plus-h></span>'+lblAdd);
        showRange($("#isRange").val())  ;       
       $("#AjaxZip").show(); 
}
function showRange(val){
    if(val=='Yes'){
         $("#IsNotRange").hide(); 
         $("#IsRange").show(); 
    }else {
          $("#IsNotRange").show(); 
         $("#IsRange").hide(); 
    }
}
function tableHeadToggle()
{
   curZoneType	=	$('input[name=deliveryZoneType]:checked').val();
   $('#state01,#zipcode01').hide();$('#Zonehead').show();
   if(curZoneType=='National') {
       $('#state01').hide();$('#zipcode01').hide();
   }else  if(curZoneType=='Region') {
       $('#state01').show();$('#zipcode01').hide();
   }
   else  if(curZoneType=='Location') {
       $('#state01').show();$('#zipcode01').show();
   }
}
function designChanges(curZoneType)
{
    if(curZoneType=='National'){
		  $('#AddCountry').addClass('national00');	
		  $('.country-select ').css("width","60%");			 	   
		}else{
		   $('#AddCountry').removeClass('national00');		   
		}
		if(curZoneType=='Region'){
		  $('.country-select ').css("width","71%");		 	
		  $("#country01").css("width","40%");				    
		}else{		  
		  $("#country01").css("width","40%");		  
		}
		if(curZoneType=='Location'){
		  $('.country-select ').css("width","98%");
		  $(".select-state").addClass("location01");			  
		}else{
		  $(".select-state").removeClass("location01");				  
		}
}
function editStateAjax(cntry,state,row,th)
{
    if(row){
        if(row=='zip'){
            $('#states_list_'+cntry+' tr').each(function(){
                
                var oldID = ($(this).attr("id"));
                var res = oldID.replace(/_zip/g, "");
                $(this).attr("id",res);
            })
            $(th).parent().parent().attr("id","right_state"+cntry+"_"+state+"_"+row);
        }
        $('#AddCountry').val(cntry);
        $('#editZipAction').val(row);
        $('#addNewCountry').html(lblEdit);
		$('#addNewCountry').addClass("edit");
        listStates(cntry,state,row,th);       
    }
}
function cancelEdit()
{
    setCountry(0);
    $('#addNewCountry').html('<span class=plus-v></span><span class=plus-h></span>'+lblAdd);
	$('#addNewCountry').removeClass("edit");
}