/**
 * Markers.
 *
 * @package fwdmgz
 * @since fwdmgz 1.0
 */

jQuery(document).ready(function($){

	'use strict';

	// Get and manage data array.
	var mainPlaylistsAr = unescapeHtml(fwdmgzMainPlaylistsAr);
  	if(mainPlaylistsAr == 'null'){
		mainPlaylistsAr = []
	}else{
		mainPlaylistsAr = JSON.parse(mainPlaylistsAr);
	}
  	if(!mainPlaylistsAr) mainPlaylistsAr = [];
	
	 $("#update_btn").click(function(){
    	$("#marker_data").val(JSON.stringify(mainPlaylistsAr));
    });
	
	$("#thtext").height(181);
	$("#thtextedit").height(181);
	$("#marher_th").hide();
	
	$(".fwd-marker").mouseover(function(){
		$(this).addClass("pr_over");
		$(this).find(".pl-header").css("color", "#212121");
	});
	
	$(".fwd-marker").mouseout(function(){
		$(this).removeClass("pr_over");
		$(this).find(".pl-header").css("color", "#555555");
	});
	
	var imgPath = fwdmgzIconsPath + "marker-icon.png";
	var img = "<img src='" + imgPath + "'>";
	$(".fwd-item > h3").prepend(img);
	$(".marker-header .ui-accordion-header-icon").css("left", "22px");

	$(".items").sortable({
        axis: "x,y",
        handle: ".item-header",
        start: startItemesOrder,
        update: updateItemesOrder
    });
	
	if ($("#main_markers .fwd-item").length > 0){
		$("#mp_em").hide();
	}
	
	$("img").fwdTooltip({});
	
	function startPlaylistsOrder(ev, ui){
		var allMpItems = $(this).sortable("toArray");	
		curPlOrderId = allMpItems.indexOf($(ui.item).attr("id"));
	}
	
	function updatePlaylistsOrder(ev, ui){
		var allMpItems = $(this).sortable("toArray");
   		newPlOrderId = allMpItems.indexOf($(ui.item).attr("id"));
   		
   		var curItem = mainPlaylistsAr.splice(curPlOrderId, 1)[0];
   	    mainPlaylistsAr.splice(newPlOrderId, 0, curItem);
	};
	
	function startItemesOrder(ev, ui){
		var allItemItems = $(this).sortable("toArray");
		curItemOrderId = allItemItems.indexOf($(ui.item).attr("id"));
	}
	
	function updateItemesOrder(ev, ui){
		var allItemItems = $(this).sortable("toArray");
   		newItemOrderId = allItemItems.indexOf($(ui.item).attr("id"));
		
   		var allPlItems = $("#main_markers").sortable("toArray");
   		var plParent = $(this).closest(".marker");
		
   		curPlOrderId = allPlItems.indexOf($(plParent).attr("id"));
   		var curItem = mainPlaylistsAr[curPlOrderId].items.splice(curItemOrderId, 1)[0];
		mainPlaylistsAr[curPlOrderId].items.splice(newItemOrderId, 0, curItem);
	}
	
    function checkLength(tips, el, prop, min, max){
      	if ((el.val().length > max) || (el.val().length < min)){
        	el.addClass("ui-state-error");
        	updateTips(tips, "Length of " + prop + " must be between " + min + " and " + max + ".");
        	
        	return false;
      	}else{
        	return true;
      	}
	}

	function checkIfFloatAndLength2(tips, el, prop, min, max){
    	var float_reg_exp = /[0-9]*\.?[0-9]+/;
    	var str = el.val();
    	var res = str.match(float_reg_exp);
    	
    	if (res && (res[0] == str)){
    		if ((el.val().length > max) || (el.val().length < min)){
            	el.addClass("ui-state-error");
            	updateTips(tips, "Length of " + prop + " must be between " + min + " and " + max + ".");
            	
            	return false;
          	}else{
            	return true;
          	}
        }else{
        	el.addClass("ui-state-error");
        	updateTips(tips, "The " + prop + " field value must be a float number.");
        	
        	return false;
        }
	}
	
    function checkIfIntegerAndLength(tips, el, prop, min, max){
    	var int_reg_exp = /-?[0-9]+/;
    	var str = el.val();
    	var res = str.match(int_reg_exp);
    	
    	if (res && (res[0] == str)){
    		if ((el.val().length > max) || (el.val().length < min)){
            	el.addClass("ui-state-error");
				updateTips(tips, "Length of " + prop + " must be between " + min + " and " + max + ".");
            	return false;
          	}else{
            	return true;
          	}
        }else{
        	el.addClass("ui-state-error");
        	updateTips(tips, "The " + prop + " field value must be an integer.");
        	return false;
        }
	}

	function updateTips(tips, txt){
	    tips.text(txt).addClass("ui-state-highlight");

	    setTimeout(function(){
	    	tips.removeClass("ui-state-highlight", 1500);
	    }, 500);
	    
	    tips.addClass("fwd-error");
	}
	

	// Marker dialogs.
	$("#add_main_marker_btn").click(function(e){
		e.preventDefault();
        $("#add-marker-dialog").dialog("open");
    });
	
	$( "#marker_type" ).change(function() {
	  if($(this).val() == "link"){
		  $("#link_type").show();
		  $("#marher_th").show();
		  $("#window_width_div").hide();
		  $("#add-marker-dialog").height(544);
	  }else if($(this).val() == "tooltip-plus" || $(this).val() == "tooltip-play"){
		   $("#link_type").hide();
		   $("#marher_th").show();
		    $("#window_width_div").show();
		   $("#add-marker-dialog").height(560);
	  }else if($(this).val() == "infowindow"){
		   $("#link_type").hide();
		   $("#marher_th").show();
		   $("#window_width_div").hide();
		   $("#add-marker-dialog").height(504);
	  }
	  $("#add-marker-dialog").dialog("option", "position", {my: "center", at: "center", of: window});
	});
	
	var curPlOrderId;
	var newPlOrderId;
	var cur_pr_id;
	var pr_name = $("#pr_name");
    var pr_type = $("#pr_type");
	var pr_source = $("#pr_source");
	var show_after_zoom_edit = $("#show_after_zoom_edit");
	var show_after_zoom = $("#show_after_zoom");
	var pr_name_edit = $("#pr_name_edit");
    var pr_type_edit = $("#pr_type_edit");
	var pr_source_edit = $("#pr_source_edit");
	var allFieldsPl = $([]).add(pr_name).add(marker_url).add(window_width).add(show_after_zoom);
	var allFieldsPlEdit = $([]).add(pr_name_edit).add(marker_url_edit).add(window_width_edit).add(show_after_zoom_edit);
	
	$("#add-marker-dialog").dialog({
		autoOpen: false,
		width: 600,
	    height: 280,
	    dialogClass:'fwdmgz',
	    modal: true,
	    buttons:[{
	        text:fwdmgzAddMarker__,
	        click: function(){
	         	
				var fValid = true;
	         	var tips = $("#add_pr_tips");
	         	
	          	allFieldsPl.removeClass("ui-state-error");
	          	fValid = fValid && checkLength(tips, pr_name, "marker name", 1, 64);
	          	fValid = fValid && checkIfFloatAndLength2(tips, show_after_zoom, "show after zoom", 1, 64);
				
				for(var i=0; i<mainPlaylistsAr.length; i++){
					if(mainPlaylistsAr[i].name == pr_name.val()){
						pr_name.addClass("ui-state-error");
						updateTips(tips, "Please make sure the marker name is unique.");
						return;
					}
				}
				
				if($("#marker_type" ).val() == "link"){
					fValid = fValid && checkLength(tips, $("#marker_url"), "URL", 1, 200);
				}else if($("#marker_type" ).val() == "tooltip-plus" || $("#marker_type" ).val() == "tooltip-play"){
					fValid = fValid && checkIfIntegerAndLength(tips, $("#window_width"), "marker window width", 1, 64);
				}
				
				if (fValid){
					
					var pid = $("#main_markers .fwd-item").length;
	          		var plsIdsAr = [];
	          		
	          		if (pid > 0){
	          			$.each(mainPlaylistsAr, function(i, el){
							plsIdsAr.push(el.id);
						});

    	          		for (var i=0; i<mainPlaylistsAr.length; i++){
    	          			if($.inArray(i, plsIdsAr) == -1){
    	          				pid = i;
    	          				break;
    	          			}
    	          		}
	          		}else{
	          			$("#mp_em").hide();
	          		}
					
					$("#main_markers").append("<div id='pl" + pid + "' class='fwd-item'>"
						+ "<h3 class='item-header'><span>" + pr_name.val().replace(/"/g, "'") + "</span></h3>"
						+ "<div>"
						+ "<button class='edit_marker_btn' id='pl" + pid + "_edit_btn'>" + fwdmgzEditMarker_+ "</button>"
						+ "<button class='delete_marker_btn' id='pl" + pid + "_del_btn'>" + fwdmgzDeleteMarker_ + "</button>"
						+ "</div>"
					+ "</div>");
					
					var imgPath = fwdmgzIconsPath + "marker-icon.png";
					var img = "<img src='" + imgPath + "'>";
					$(("#pl" + pid) + " > h3").prepend(img);
					
					$(".edit_marker_btn, .edit_marker_btn2").click(function(e){
						
						e.preventDefault();
					
						var reg_exp1 = /pl[0-9]+_/;
					
						cur_pr_id = parseInt($(this).attr("id").match(reg_exp1)[0].slice(2, -1));
						
						var allMpItems = [];
						for(var i=0; i<$("#main_markers").children().length; i++){
							allMpItems.push($("#main_markers").children()[i].getAttribute("id"))
						}
			
						curPlOrderId = allMpItems.indexOf("pl" + cur_pr_id);
						
						$("#edit-marker-dialog").dialog("open");
					});
				
					$(".delete_marker_btn, .delete_marker_btn2").click(function(e){
						e.preventDefault();
					
						var reg_exp = /pl[0-9]+_/;
						cur_pr_id = parseInt($(this).attr("id").match(reg_exp)[0].slice(2, -1));
						
						$("#delete-marker-dialog").dialog("open");
					});

					$(".marker .ui-accordion-header-icon").css("left", "22px");
					var htmlText = getInfoText();
				
					var newPl ={
						id:pid,
						name: pr_name.val().replace(/"/g, "'"),
						regpoint:$("#reg_point").val().replace(/"/g, "'"),
						url:$("#marker_url").val().replace(/"/g, "'"),
						target:$("#link_target").val().replace(/"/g, "'"),
						type:$("#marker_type").val().replace(/"/g, "'"),
						window_width:parseInt($("#window_width").val().replace(/"/g, "'")),
						dataZoomAfterFactor:$("#show_after_zoom").val().replace(/"/g, "'"),
						text:htmlText
					};
				
					mainPlaylistsAr.push(newPl);
					
					$(this).dialog("close");
				}
	         	 
	        }},
	        {
	       	text:fwdmgzCancel__,
	        click: function() {
	        	$(this).dialog("close");
	        }}
	    ],
	    close: function(){
		    allFieldsPl.removeClass("ui-state-error");  
		    $("#add_pr_tips").removeClass("fwd-error");
	    },
	    open: function(){
			$("#pr_name").val("");
			$("#marker_type").val("link");
	    	$("#marker_url").val("");
			$("#link_target").val("_blank");
			$("#window_width").val("");
			$("#reg_point").val("center");
			$("#link_type").show();
			$("#marher_th").show();
			$("#window_width_div").hide();
			$("#show_after_zoom").val(0);
			$("#add-marker-dialog").height(550);
			$("#add-marker-dialog").dialog("option", "position", {my: "center", at: "center", of: window});
			setInfoText("");
		}
	});
	
	$(".add_marker_btn").click(function(e){
		e.preventDefault();
		var reg_exp = /mp[0-9]+_/;
		cur_pr_id = parseInt($(this).attr("id").match(reg_exp)[0].slice(2, -1));
        $("#add-marker-dialog").dialog("open");
    });
    
	$("#edit-marker-dialog").dialog({
		autoOpen: false,
		width: 600,
	    height: 325,
	    dialogClass:'fwdmgz',
	    modal: true,
	    buttons:[{
	        text:fwdmgzUpdateMarker__,
	        click: function(){
				var fValid = true;
				var tips = $("#add_pr_tips_edit");
				
				allFieldsPlEdit.removeClass("ui-state-error");
				
				fValid = fValid && checkLength(tips, pr_name_edit, "marker name", 1, 64);
				fValid = fValid && checkIfFloatAndLength2(tips, show_after_zoom_edit, "show after zoom", 1, 64);
				
				if($("#marker_type_edit").val() == "link"){
					fValid = fValid && checkLength(tips, $("#marker_url_edit"), "URL", 1, 200);
				}else if($("#marker_type_edit").val() == "tooltip-plus" || $("#marker_type_edit").val() == "tooltip-play"){
					fValid = fValid && checkIfIntegerAndLength(tips, $("#window_width_edit"), "marker window width", 1, 64);
				}
		 
				if (fValid){
					var content = $("#pl" + cur_pr_id + " > h3").html();
	          		var pos = content.indexOf(mainPlaylistsAr[curPlOrderId].name + "<") 
					content = content.slice(0, pos);
	          		$("#pl" + cur_pr_id + " > h3").html(content + pr_name_edit.val().replace(/"/g, "'"));
					
					mainPlaylistsAr[curPlOrderId].regpoint = $("#reg_point_edit").val().replace(/"/g, "'");
					mainPlaylistsAr[curPlOrderId].dataZoomAfterFactor = $("#show_after_zoom_edit").val().replace(/"/g, "'");
					
					if(mainPlaylistsAr[curPlOrderId].type == "link"){
						mainPlaylistsAr[curPlOrderId].url = $("#marker_url_edit").val().replace(/"/g, "'");
						mainPlaylistsAr[curPlOrderId].target = $("#link_target_edit").val();
						mainPlaylistsAr[curPlOrderId].text = getInfoTextEdit();
					}else if(mainPlaylistsAr[curPlOrderId].type == "tooltip-plus" || mainPlaylistsAr[curPlOrderId].type == "tooltip-play"){
						mainPlaylistsAr[curPlOrderId].window_width = $("#window_width_edit").val();
						mainPlaylistsAr[curPlOrderId].text = getInfoTextEdit();
					}else if(mainPlaylistsAr[curPlOrderId].type == "infowindow"){
						mainPlaylistsAr[curPlOrderId].text = getInfoTextEdit();
					}
					
					$(this).dialog("close");
				}
	        }},
	        {
	        text:fwdmgzCancel__,
	        click: function(){
	        	$(this).dialog("close");
	        }}
	    ],
	    close: function(){
		    allFieldsPlEdit.removeClass("ui-state-error");
		    $("#add_pr_tips_edit").removeClass("fwd-error");
	    },
	    open: function(){
			$("#add_pr_tips_edit").text("The marker name is required:");
			$("#pr_name_edit").css({"opacity":".5", "pointer-events":"none"});
			$("#pr_name_edit").val(mainPlaylistsAr[curPlOrderId].name);
			$("#marker_type_edit").css({"opacity":".5", "pointer-events":"none"});
			$("#marker_type_edit").val(mainPlaylistsAr[curPlOrderId].type);
			$("#reg_point_edit").val(mainPlaylistsAr[curPlOrderId].regpoint);
			$("#show_after_zoom_edit").val(mainPlaylistsAr[curPlOrderId].dataZoomAfterFactor);
			
		if(mainPlaylistsAr[curPlOrderId].type == "link"){
			  $("#link_type_edit").show();
			  $("#marher_th_edit").show();
			  $("#window_width_div_edit").hide();
			  $("#marker_url_edit").val(mainPlaylistsAr[curPlOrderId].url);
			  $("#link_target_edit").val(mainPlaylistsAr[curPlOrderId].target);
			  setInfoTextEdit(mainPlaylistsAr[curPlOrderId].text);
			  $("#edit-marker-dialog").height(544);
		  }else if(mainPlaylistsAr[curPlOrderId].type == "tooltip-plus" || mainPlaylistsAr[curPlOrderId].type == "tooltip-play"){
			   $("#link_type_edit").hide();
			   $("#marher_th_edit").show();
			   $("#window_width_div_edit").show();
			   $("#window_width_edit").val(mainPlaylistsAr[curPlOrderId].window_width);
			   setInfoTextEdit(mainPlaylistsAr[curPlOrderId].text);
			   $("#edit-marker-dialog").height(560);
		  }else if(mainPlaylistsAr[curPlOrderId].type == "infowindow"){
			   $("#link_type_edit").hide();
			   $("#marher_th_edit").show();
			   $("#window_width_div_edit").hide();
			   setInfoTextEdit(mainPlaylistsAr[curPlOrderId].text);
			   $("#edit-marker-dialog").height(504);
		  }
		  $("#edit-marker-dialog").dialog("option", "position", {my: "center", at: "center", of: window});
		}
	});

	
	$(".edit_marker_btn, .edit_marker_btn2").click(function(e){
		e.preventDefault();
	
		var reg_exp1 = /pl[0-9]+_/;
		cur_pr_id = parseInt($(this).attr("id").match(reg_exp1)[0].slice(2, -1));
		
		var allMpItems = [];
		for(var i=0; i<$("#main_markers").children().length; i++){
			allMpItems.push($("#main_markers").children()[i].getAttribute("id"))
		}
		
		curPlOrderId = allMpItems.indexOf("pl" + cur_pr_id);
		$("#edit-marker-dialog").dialog("open");
	});
	
	$("#delete-marker-dialog").dialog({
		autoOpen: false,
		width: 300,
	    height: 160,
	    dialogClass:'fwdmgz',
	    modal: true,
	    buttons:[{
	        text: fwdmgzYes__,
	        click: function(){
				var allMpItems = [];
				for(var i=0; i<$("#main_markers").children().length; i++){
					allMpItems.push($("#main_markers").children()[i].getAttribute("id"))
				}
	            
	       		curPlOrderId = allMpItems.indexOf("pl" + cur_pr_id);
	       		mainPlaylistsAr.splice(curPlOrderId, 1);
	       		
	       		$("#pl" + cur_pr_id).remove();
				
				if ($("#main_markers .fwd-item").length == 0){
	            	$("#mp_em").show();
	            }
	            $(this).dialog("close");
	        }},
	        {
	        text:fwdmgzNo__,
	        click: function(){
	        	$(this).dialog("close");
	        }}
	    ]
	});
	
	$(".delete_marker_btn, .delete_marker_btn2").click(function(e){
		e.preventDefault();
		var reg_exp = /pl[0-9]+_/;
		cur_pr_id = parseInt($(this).attr("id").match(reg_exp)[0].slice(2, -1));
		$("#delete-marker-dialog").dialog("open");
	});

	
	function setInfoText(str){
		if (tinyMCE.get("thtext")){
	    	tinyMCE.get("thtext").setContent(str);
	    }
	    $("#thtext").val(str);
	}
	
	function getInfoText(){
		var th_text;
		
		if (tinyMCE.get("thtext")){
			if ($("#wp-thtext-wrap").hasClass("tmce-active")){
				th_text = tinyMCE.get("thtext").getContent();
				
				if (th_text.length < 1){
					th_text = $("#thtext").val();
				}
			}else{
				th_text = $("#thtext").val();
			}
	    }else{
			th_text = $("#thtext").val();
		}

        return th_text.replace(/"/g, "'").replace(/\n/g, "");
	}
	
	
	function setInfoTextEdit(str){
		if (tinyMCE.get("thtextedit")){
	    	tinyMCE.get("thtextedit").setContent(str);
	    }
	    
	    $("#thtextedit").val(str);
	}
	
	function getInfoTextEdit(){
		var th_text;
		
		if (tinyMCE.get("thtextedit")){
			if ($("#wp-thtextedit-wrap").hasClass("tmce-active")){
				th_text = tinyMCE.get("thtextedit").getContent();
				
				if (th_text.length < 1){
					th_text = $("#thtextedit").val();
				}
			}else{
				th_text = $("#thtextedit").val();
			}
	    }else{
			th_text = $("#thtextedit").val();
		}

        return th_text.replace(/"/g, "'").replace(/\n/g, "");
	}

	// Utils.
	function updateTips(tips, txt){
	    tips.text(txt).addClass("ui-state-highlight");

	    setTimeout(function(){
	    	tips.removeClass("ui-state-highlight", 1500);
	    }, 500);
	    
	    tips.addClass("fwd-error");
	}

    function escapeHtml(str) {
	    var map = {
	        "&": "&amp;",
	        "<": "&lt;",
	        ">": "&gt;",
	        "\"": "&quot;",
	    "'": "&#039;"
	    };
	    str = str.replace(/'/g, "\"");
	    return str.replace(/[&<>"']/g, function(m) { return map[m]; });
	}

	function unescapeHtml(str) {
	    var map = {
	        "&amp;": "&",
	        "&lt;": "<",
	        "&gt;": ">",
	        "&quot;": "\"",
	        "&#039;": "'"
	    };
	    return str.replace(/(&amp;|&lt;|&gt;|&quot;|&#039;)/g, function(m) { return map[m]; });
	}
	
});