$(document).ready(function() {
if($('#menuItemID').val() > 0) {
		checkParentlanguageIDs();
		
	}
   $(".cntntlanguage").change(function () {
        checkParentlanguageIDs();
    })
//change status of menu item
$(".changeItemStatus").click(function () {	
	  var ID=$(this).attr("id");
	  var newstatus=$(this).attr("rel");
	  var orderID=$(this).attr("orderid");
	  if(orderID > 0)  
			var statusLink =  'orderID=' +orderID + '&newstatus=' + newstatus;
		else
			var statusLink =  'itemId=' +ID + '&newstatus=' + newstatus;
	    $.ajax({
        type: "POST",
        data: statusLink,
        url: GLOBAL_BASE_PATH + "/custommenu/ajaxchangeStatus/",
        success: function (data) { 
			location.reload();
			}
    })
});

$("[task=deleteItem]").click(function(){
		var ID=$(this).attr('id');
		var count = $(this).attr('child');
		var menuID = $('#menuID').val();
		var lang = $('#lang').val();
		lang = (lang!='') ? lang : 0;
		var brandID = $('#brandID').val();
		var orderID=$(this).attr("orderid");
		var obj = $(this).closest('li').find('li');
		var subItems =  ((count > 0) && (orderID > 0)) ? subItemsText: '';
		jConfirm(subItems + msgDeleteMenuItems,deleteText, function(r) {
	   		if(r==true)
				{
				if(orderID > 0)  {
					window.location=GLOBAL_BASE_PATH+"/custommenu/destroymenuitem/orderID/"+orderID+"/menuID/"+menuID+"/lang/"+lang+"/brandID/"+brandID;
				}else {
					if(count > 0)
						jNotifyShow(errDeleteItemsWithChild+subItemsText, "common_message","message_error");
					else
						window.location=GLOBAL_BASE_PATH+"/custommenu/destroymenuitem/itemId/"+ID+"/brandID/"+brandID;
				}
				}
			});
});

var paramStore={}; 
//function to call ajax functions when language is changed
$('#specificLangDiv input[type="checkbox"]').click(function() {
	 refreshMenuItemSettings();
	refreshParentItems();
});

$('.AllLangOptions').click(function(){  
    checkParentlanguageIDs();
    refreshMenuItemSettings();
     refreshParentItems();
  
});
$('#brandID').change(function(){  
if($('#brandID').val() > 0) {
    checkParentlanguageIDs();
    refreshMenuItemSettings();
     refreshParentItems();
}  
});
function refreshMenuItemSettings()
{
    var itemTypeID = $('#menuItemType').val();
    var brandID = $('#brandID').val();
	var itemType = $('#menuItemType option:selected').attr('modKey');
         var allLang=$('input:radio[name="langSelect"]:checked').val();
    if(allLang=='Yes'){ var selLanguages = ['0']; }else {
        var selLanguages = [];       
        $('#specificLangDiv input[type="checkbox"]:checked').each(function () {
                selLanguages .push($(this).val());
        });
    }
	//var selLanguages =  $.map($('#selectedLang option:selected'),function(elem) { return elem.value; });
	if((itemType=='singlepage'  || itemType=='blog'|| itemType=='singlecategory')) {
		var paramsKey = 'type:'+itemTypeID +'-'+'lang:'+selLanguages +'-'+'brand:'+brandID ;
		var defaultData	 = 	(selmoduleID == itemType) ? paramsEncoded : '';                
		if(typeof paramStore[paramsKey]=="undefined") {
			$.ajax({
				type : "POST",
				data : "type=" + itemTypeID + "&defaultData=" + defaultData + "&selLanguages=" + selLanguages + "&brandID=" + brandID ,
				url  :  GLOBAL_BASE_PATH + "/custommenu/ajaxMenuItemSettings/",
				success : function (data) {
					paramStore[paramsKey]=$.trim(data);
					$('#reqSettings').html(data);
					CreateTargetUrl(itemType);
				}
			});
		}
		else {
			$("#reqSettings").html(paramStore[paramsKey]);
			CreateTargetUrl(itemType);
		}
	}
}
function refreshParentItems()
{
    var listItems = '';
	var menuItemID=$('#menuItemID').val();
	var parentID=$('#parentID').val();
	var brandID=$('#brandID').val();
	//var selLanguages = $('#selectedLang option:selected').val();
         var allLang=$('input:radio[name="langSelect"]:checked').val();
          var selLanguages = [];    
    if(allLang=='Yes'){ }else {	    
        $('#specificLangDiv input[type="checkbox"]:checked').each(function () {
                selLanguages .push($(this).val());
        });
    }
	 $.ajax({
        type: "POST",
        data: '&itemId=' + menuItemID + "&selLanguages=" + selLanguages + "&parentID=" + parentID+"&AllLang="+$('input[type="radio"]:checked').val()+ "&brandID=" + brandID,
        url: GLOBAL_BASE_PATH + "/custommenu/ajaxListMenuItems/",
        success: function (data) {
			listItems = '<option value="">'+ lblRootLevel +'</option>';
			listItems += (data) ? data : '';
			$('#parent').html(listItems);
			}
    })
	
}
//To load the required settings section according to the modules selected
$('#menuItemType').change(function() {
	$('#itemTypeSel').val('');
	$('#link').removeAttr('readonly');
	var itemType = $('#menuItemType option:selected').attr('modKey');
        if(itemType=='text'){
            $('.AjaxLinkDiv').attr('style','display:none');
        } else {
            $('.AjaxLinkDiv').attr('style','display:block');
        }
		if(itemType=='productlist'){
        $('.AjaxSetCMSSourceUrl').attr('style','display:none');
	} else if(itemType=='singlepage' || itemType=='customerservice' || itemType=='singlecategory'){
        $('.AjaxSetCMSSourceUrl').attr('style','display:block');
    }else {
        $('.AjaxSetCMSSourceUrl').attr('style','display:none');
	}
	if($('#menuItemType').val() > 0 && itemType!='text') {
		$('#itemTypeKey').val($('#menuItemType option:selected').attr('modKey'));
		//No need to show RP checbox  if menu item types - External URL, Text Separator, Static Text.
		if($.in_array($('#menuItemType option:selected').attr('modKey'), ['seperator', 'text', 'url'])) {
			$('#redirectDiv').attr('style','display:none');
		}
		else $('#redirectDiv').attr('style','display:block');
		
		$('#link').val($('#menuItemType option:selected').attr('link'));
		if($('#menuItemType option:selected').attr('modKey')!='url') $('#link').attr('readonly', 'readonly');//external url
		if($('#menuItemType option:selected').attr('modKey')!='singlepage') {
                    $( "li.first-item" ).nextAll().hide();
                    $('li.ajaxRelatedMenuDiv').hide();
                }else {
                     $( "li.first-item" ).nextAll().show();
                     $('li.ajaxRelatedMenuDiv').show();
                }
		if($('#menuItemType option:selected').attr('params') == '1') {
			$('#itemTypeSel').val($('#menuItemType').val());
			var itemType = $('#menuItemType option:selected').attr('modKey');
			var itemTypeID = $('#menuItemType').val();			
			var brandID = $('#brandID').val();			
			var defaultData	 = 	(selmoduleID == itemType) ? paramsEncoded : '';
			//var selLanguages = $('#selectedLang option:selected').val();
                         var allLang=$('input:radio[name="langSelect"]:checked').val();
                    if(allLang=='Yes'){ var selLanguages = ['0']; }else {
                         var selLanguages = [];                        
                        $('#specificLangDiv input[type="checkbox"]:checked').each(function () {
                                selLanguages .push($(this).val());
                        });
                    }
			var paramsKey = (itemType=='singlepage' || itemType=='blog') ? 'type:'+itemTypeID +'-'+'lang:'+selLanguages +'-'+'brand:'+brandID :'type:'+itemTypeID;
			if(typeof paramStore[paramsKey]=="undefined") {
				$.ajax({
					type : "POST",
					data : "type=" + itemTypeID + "&defaultData=" + defaultData + "&selLanguages=" + selLanguages + "&brandID=" + brandID,
					url  :  GLOBAL_BASE_PATH + "/custommenu/ajaxMenuItemSettings/",
					success : function (data) {
						paramStore[paramsKey]=$.trim(data);
						$('#mainSettings').attr('style','display:block');
						$('#reqSettings').html(data);
						CreateTargetUrl(itemType);
					}
				});
			}
			else {
				
				$("#reqSettings").html(paramStore[paramsKey]);
				CreateTargetUrl(itemType);
			}
		}
		else
		{
			$('#reqSettings').html('');			
		}	
		$('#mainSettings').attr('style','display:none');
	}
	else
		$('#link').val('');
		$('#mainSettings').attr('style','display:none');
		
	if(typeof paramStore[paramsKey]!="undefined") { $('#mainSettings').attr('style','display:block');}
	setProductFilterSection();
});
$('#menuItemKey').change(function(){	
	// Permanent Redirect
	if(settingsRedirectUrl == 'Yes') {
		if($("#menuItemKey").val()!=$("#menuItemKeyOld").val()) 
			$("#redirectOption").removeAttr('disabled');
		else {
			$("#redirectOption").attr("disabled", "true");
		}
	}
});
 

if(menuItemAction=="menuItemAdd") {	
	$('#itemTypeKey').val($('#menuItemType option:selected').attr('modKey'));
	//No need to show RP checkbox if menu item types - External URL, Text Separator, Static Text. 
	if($.in_array($('#menuItemType option:selected').attr('modKey'), ['seperator', 'text', 'url'])) 
		 $('#redirectDiv').attr('style','display:none');
	else $('#redirectDiv').attr('style','display:block');
}	
$(document).on("change", "#settings_selectedID", function() {
	var itemtype	=	 $('#menuItemType option:selected').attr('modKey');
	CreateTargetUrl(itemtype);
       
});
function CreateTargetUrl(itemType) {
	var value = $('#menuItemType option:selected').attr('link');
	switch (itemType) { 

    case 'singlepage': 
		 $('#link').val('');
		 if ($('#settings_selectedID option:selected').val() > 0) {
                    $('#link').val(value + 'id/' + $('#settings_selectedID option:selected').val()+'/');
		 }
        break;
     case 'blog': 
		 $('#link').val('');
		 if ($('#settings_selectedID option:selected').val() > 0) {
                    $('#link').val(value + 'id/' + $('#settings_selectedID option:selected').val()+'/');
		 }
        break;
    case 'singlecategory':
		 //$('#link').val(value + 'id/' +  $('#settings_selectedID option:selected').val()+'/');                 
		 $('#link').val(value + $('#settings_selectedID option:selected').val()+'/');                 
                 break;
    case 'blogCategory':
		 $('#link').val(value  +  $('#settings_selectedID option:selected').val()+'/');     
         break;
	case 'singlebrand':
	case 'singlestore':
		$('#link').val(value +  $('#settings_selectedID option:selected').attr('key')+'/');
		break;
	}
}


$("#submit").click(function(){
	if($('#menuItemID').val() > 0) {
		checkParentlanguageIDs();
		
	}
	 //To display error when no value is selected.In case of cms pages,product types,product categories.
		if($('#settings_selectedID').val()<1) {
			 jAlert(SelectMenuItemTypeDetails);
			 return false;
	    }
});
 //To validate parent menu item language change.
function checkParentlanguageIDs() {
    //Module check section 
    var itemType = $('#menuItemType option:selected').attr('modKey');
        if(itemType=='text'){
            $('.AjaxLinkDiv').attr('style','display:none');
        } 
        //module ends
	$("#hiddenParentLangCheck").val(0);
         $("#hiddenLangCheck").val(0);      
        var allLang=$('input:radio[name="langSelect"]:checked').val();
        var selLanguages = [];    
        var orderchildsLanguagesArr	=	[];
	var childrenLanguagesArr			=	[];
    if(allLang=='Yes'){ 
        var selected = '0'; 
        $("#hiddenLangCheck").val(0);                              
        $("#checkContentLang").trigger('blur');  
    }else {   
        var selected = '';
        $('#specificLangDiv input[type="checkbox"]:checked').each(function () {
                selLanguages .push($(this).val());
        });        
    }   
     if(selLanguages.length>0){
             $("#checkLangSelect").val(1);
         }else {
              $("#checkLangSelect").val('');
         }
         $("#checkLangSelect").trigger('blur');         
    if((selected!='0') )  {
               var content = $('#currentContentLanguageID').val();
               //check content languaage & selected language
                if((selLanguages.indexOf(content))== -1){
                    $("#hiddenLangCheck").val(1);                              
                    $("#checkContentLang").trigger('blur');                    
                } 
                // check parent - children lang 
                if(children > 0 || orderchilds > 0) {
                      if(orderchildsLanguages!='')
                        orderchildsLanguagesArr 	= 	orderchildsLanguages.toString().split(","); 
                    if(childrenLanguages!='')
                        childrenLanguagesArr 	= 	childrenLanguages.toString().split(","); 
                   
                    if(($.intersect(orderchildsLanguagesArr,selLanguages).length != orderchildsLanguagesArr.length && orderchildsLanguagesArr.length!=0)){
                        $("#hiddenParentLangCheck").val(1);
                        $("#checkParentLang").trigger('blur');
                    } 
                    
                    if(($.intersect(childrenLanguagesArr,selLanguages).length != childrenLanguagesArr.length && childrenLanguagesArr.length!=0)){
                       $("#hiddenParentLangCheck").val(1);
                        $("#checkParentLang").trigger('blur');
                    } 
                 
                 }
                        
	} 
        return false;
 } 
$("#submitSearch").click(function(){
		var menuID=$("#menuID").val();
	   	if(menuID=='')	{
			jAlert(msgSelectSearchCriteria);
			return false;
		}
});
$("#submitItems").click(function () {
				var menuID=$('#menuID').val();
				var brandID=$('#brandID').val();
				$.ajax({
					type:"POST",
					async: false,
					data: 'items=' + $.stringify(parseTree($("#sort1"),0,0)) + "&menuID=" + menuID+ "&brandID=" + brandID,
					url:GLOBAL_BASE_PATH + "/custommenu/ajaxListOrderItems/"
				}).done(function(){
					location.reload(); 
				});	
});	
$("#submitItemDetails").click(function () {
				$.ajax({
					type:"POST",
					async: false,
					 data: 'items=' + $.stringify(parseTree($("#sort1"),0,0)) ,
					 url:GLOBAL_BASE_PATH + "/custommenu/ajaxListOrderParentItems/",
					 success : function (data) { 
					 location.reload(); 
					 }
				})
});
var item={}; 
//function to show source data of a menu item.
$(".type_details").mouseover(function () {
	var ID=$(this).attr('itemid');
	var moduleID=$(this).attr('moduleid');
        var closestLi = $(this) .closest( "li" );
        var closestLiLang=closestLi.data('lang');
        if(closestLiLang!=null && closestLiLang!='0'){
            var closestLiLanguages 	= 	closestLiLang.toString().split(",");
            var lang =closestLiLanguages[0];
        } else {
            var lang ='0';
        }
if($("#lang").val() >= 0 ) {
		var lang = $("#lang").val();
	} else var lang = '';
	if(typeof item[ID]=="undefined") {
				$.ajax({
					type:"POST",
					async: false,
					 data: 'itemId=' + ID + "&moduleID=" + moduleID + "&lang=" + lang,
					 url:GLOBAL_BASE_PATH + "/custommenu/ajaxGetItemTypeDetails/",
					 success : function (data) {
					 item[ID]=$.trim(data);					 
					 if($.trim(data)) {
						
						 $(".add-details-outer").show();
						 $(".add-details").html(data);
					 } 
					 }
				})
				} else {
				$(".add-details-outer").show();
				$(".add-details").html(item[ID]);
				}
});		
});
setProductFilterSection();
function setProductFilterSection()
{
	var itemType = $('#menuItemType option:selected').attr('modKey');
	if(itemType=="productfilterurl")
	{
		$('#mainSettings').attr('style','display:none');
		$('#reqSettings').html('');	
		$(".showGenerateCatalogLink").removeClass("hide");
	}
	else
	$(".showGenerateCatalogLink").addClass("hide");
}	