$(function() {
    setNavigation();
    //colorEmptyField();
    centerFixedItem("#box");
    centerFixedItem("#sendToColleague");
    centerFixedItem("#sendToAuthor");
    showDropdown();
    prepopulateFromTitle(".prePopulateFromTitle");
    preopulateInput(".simpleSearch input[type='text']", "Search");
    preopulateInput(".emailSignUpInput", "Email Address");
    moveErrorMessageOnCreateUser();
    mostCommentedAddNumbers();
    popupHandler();
    showFieldBasedOnValue("#idJobTitle", "Other (please specify below)", "#idOtherJobTitle");
    showFieldBasedOnValue("#idPrimaryPracticeArea", "Other (please specify below)", "#idOtherPracticeArea");
    showFieldBasedOnValue("#idReasonVisit", "Other (please specify below)", "#idOtherReasonVisit");
    mostCommentedRemoveSiteTitleFromItems();
    emailAlertSubscriptions();
});

/* ------------------------ JS functions for email alert subscribtions --------------------------- */
function emailAlertSubscriptions() {
	$('#emailAlertSubscriptionsForm').submit(function () { // catch the form's submit event
		if ($("#emailAlertSubscriptionsForm input:checked").length > 0) {
			alertsSelected();  // at least one alert selected
		} else {
			noAlertsSelected();// no alert selected
		}
		function alertsSelected() {
			alertsPopup("Click 'Yes' to confirm save or 'Cancel'<div class='buttons'>" +
					"<p class='button' onclick='closePopup()'>Cancel</p>" +
					"<p class='button' onclick='ajaxcallwhenchecked()'>Yes</p></div>");
		}
		function noAlertsSelected() {
			alertsPopup("You do not have any emails selected. This means you will stop receiving news updates" +
					" from Lloyd's Maritime Law Newsletter. Do you wish to continue?<div class='buttons'>" +
					"<p class='button' onclick='closePopup()'>Cancel</p>" +
					"<p class='button' onclick='ajaxcallwhennotchecked()'>Continue</p></div>");
		}
		return false;
	});	
}
function alertsPopup(contnetOfPopup) {
	$("body").prepend('<div id="emailAlertSubscriptionsPopup">'+
							'<h1>Track Your Topic</h1>'+
							'<div class="popupContent"></div>'+
					  '</div>');
	$("#emailAlertSubscriptionsPopup .popupContent").html(contnetOfPopup);
	openPopup("#emailAlertSubscriptionsPopup");
	centerFixedItem("#emailAlertSubscriptionsPopup");
}
function ajaxcallwhenchecked() {
	$.ajax({ // create an AJAX call...
		data: $('#emailAlertSubscriptionsForm').serialize(), // get the form data
		type: 'POST', // GET or POST
		url: $('#emailAlertSubscriptionsForm').attr('action'), // the file to call
		success: function (response) { // on success..
			closePopup();
			var popupHtml = "<strong>Confirmation Summary</strong><br /><br />" +
			"Thank you for choosing the following alerts:<ol>"+ listOfAlerts() +"</ol><div class='buttons'>" +
			"<p class='button' onclick='closePopup()'>Close</p></div>"
			setTimeout(function() {alertsPopup(popupHtml);}, 1000);			
		}
	});
	function listOfAlerts() {
		var list = "";
		$("#emailAlertSubscriptionsForm input:checked").each(function() {
			var name = "";
			name = $(this).attr('title');
			if (name == "") name = $(this).next().text();
			list += "<li>" + name + "</li>"
		});
		return list;
	}
}
function ajaxcallwhennotchecked() {
	$.ajax({ // create an AJAX call...
		data: $('#emailAlertSubscriptionsForm').serialize(), // get the form data
		type: 'POST', // GET or POST
		url: $('#emailAlertSubscriptionsForm').attr('action'), // the file to call
		success: function (response) { // on success..
			closePopup();
			var popupHtml = "All alerts deleted<div class='buttons'>" +
			"<p class='button' onclick='closePopup()'>Close</p></div>"
			setTimeout(function() {alertsPopup(popupHtml);}, 1000);
		}
	});
}
/* ---------------------  END of JS functions for email alert subscribtions ---------------------- */

function popupHandler() {
	$(".openPopup").click(function() {
		var buttonText = $(this).text().toLowerCase();	
		var forgotten = /forgotten/;
		var colleague = /colleague/;
		var author = /editor/;		
		if (forgotten.test(buttonText)) {
			openPopup("#box");
		};
		if (colleague.test(buttonText)) {
			openPopup("#sendToColleague");
		};
		if (author.test(buttonText)) {
			openPopup("#sendToAuthor");
		};
		return false;
	});
	$(".closePopup").click(function() {
		closePopup();
		return false;
	});
}

function openPopup(IdOfItemToPopup) {
	$("body").prepend('<div class="dark"> </div>');
    $(IdOfItemToPopup).fadeIn(2000);
    $(IdOfItemToPopup).addClass("popedUp");
}

function closePopup() {
	$(".popedUp").fadeOut(600, function() {		
		$(".dark").remove();
		if ($('#emailAlertSubscriptionsPopup') != null) $('#emailAlertSubscriptionsPopup').remove(); // additional line for email subscription popup (which is generated dynamically)
		// so we need to remove it from DOM
	});
	$(".popedUp").removeClass("popedUp");
}

function mostCommentedAddNumbers() {
	var number = 1;
	$('.dsq-widget-list li').each(function(){
		$(this).prepend('<span class="commentNumber">'+ number +'</span>');
		number++;
	})
	$('.dsq-widget-list li:last-child').css("border", "none");
}

function mostCommentedRemoveSiteTitleFromItems() {
	$('.dsq-widget-list li a').each(function(){
		var tekst =  $(this).text().replace(/-.*Lloyd's Maritime Law Newsletter$/,"");
		$(this).text(tekst);
	});
}

function moveErrorMessageOnCreateUser() {
	var errorMessageHtml = $('.createuser #main #createUserForm .errors').html();
	if (errorMessageHtml) {
		$('.createuser #main #createUserForm .errors').remove();
		$('.createuser #main').prepend('<div class="errors create"></div>');
		$('.createuser #main .errors').html(errorMessageHtml);
	};
}

function showDropdown() {
	var hide = false;
	var timeout = false;
	$( "#navigation .secondary-nav ul li" ).hover(	
		function () {			
			var currentItem = $(this);
			timeout = setTimeout(function() {dropHandle(currentItem)}, 600)
			
			function dropHandle(current) {
				var subnav = current.find(".menu-topStories").html();
				if (subnav != null) {
					if ( $(".dropdown").hasClass("to_fadein")) {
						if (hide) clearTimeout(hide);
					}
					$("#navigation").append("<div class='dropdown to_fadein'> </div>");
					var navHeight = $("#navigation").height() + 10;
					$(".dropdown").css("top",navHeight);
					$(".dropdown.to_fadein").html(subnav).fadeIn(300);
					$( "#navigation .dropdown" ).hover(
						function () {
							if (hide) clearTimeout(hide);
						},
						function () {
							fadeAndRemove();
						}
					);
				}
			}			
		},
		function () {
			fadeAndRemove();
		}
	);
	function fadeAndRemove() {
		if (timeout) clearTimeout(timeout);
		$(".dropdown").removeClass("to_fadein").addClass("to_fadeout");
		hide = setTimeout(function() {
			$(".dropdown.to_fadeout").fadeOut('slow', function() { 
				$(this).remove();
			});
		}, 50);
	}
}

function centerFixedItem(item) {
	$(item).css("position","fixed");
	$(item).css("top", ( $(window).height() - $(item).height() ) / 2 + "px");
	$(item).css("left", ( $(window).width() - $(item).width() ) / 2 + "px");
}

function colorEmptyField() {
    $("#navigation .search .button").click(function() {
		if ( $("#navigation .search .field").val() == "") {
			$("#navigation .search .field").css("background","#F6E0E2");
		}
	});
	$("#search-result .search .button").click(function() {
		if ( $("#search-result .search .field").val() == "") {
			$("#search-result .search .field").css("background","#F6E0E2");
		}
	});
}

function setNavigation() {
    var jsonCookieEncoded = $.cookie('informa_nl_session');
    var jsonCookie = $.URLDecode(jsonCookieEncoded);
    var jsonObj = jQuery.parseJSON(jsonCookie);

    if (jsonObj != null) {
        populateEmailSignUpInput(jsonObj.emailId);
        switch(jsonObj.ent)
        {
            case "0":
//                trialNav();
                //setVisitorType("trialist");
                break;
            case "1":
//                paidNav();
               // setVisitorType("subscriber");
                break;
            default:
//                anonymousNav();
                //setVisitorType("anonymous");
            	break;
        }
        if(jsonObj.emailId){
             setUserID(jsonObj.emailId);
             setEmail(jsonObj.emailId);
             //isLoggedIn("logged in");

        }
    } else {
//        anonymousNav();
        //setVisitorType("anonymous");
        //isLoggedIn("anonymous");
    }
    setPaddingOnChildItemsEqually(".primary-nav ul", "li a span");
}

function populateEmailSignUpInput(emailVal) {
	if (emailVal != null) $('input.emailSignUpInput').val(emailVal);
}

function anonymousNav() {
    $(".primary-nav ul li:nth-child(9)").remove();
    $(".primary-nav ul li:nth-child(7)").remove();
}

function trialNav() {
    $(".primary-nav ul li:nth-child(8)").remove();
    $(".primary-nav ul li:nth-child(3)").remove();
    $(".top-menu ul li:nth-child(3)").remove();
    $(".top-menu ul li:nth-child(1)").remove();
    $(".bottom-nav ul li:nth-child(1)").remove();
}

function paidNav() {
    $(".primary-nav ul li:nth-child(8)").remove();
    $(".primary-nav ul li:nth-child(4)").remove();
    $(".primary-nav ul li:nth-child(3)").remove();
    $(".top-menu ul li:nth-child(2)").remove();
    $(".top-menu ul li:nth-child(1)").remove();
    $(".bottom-nav ul li:nth-child(2)").remove();
    $(".bottom-nav ul li:nth-child(1)").remove();
}

function setPaddingOnChildItemsEqually(AreaSelector, ChildItemSelector) {
    var containerArea = $(AreaSelector);
	containerArea.find('span').each(function() {
		$(this).html( $.trim($(this).html()));
	});
    var containerWidth = parseInt(containerArea.width());
    var containerItems = containerArea.find(ChildItemSelector);
	var itemCount = containerItems.length; // how many items were found
	var itemWidthCount = countItemsWidth(containerItems);
	var freeSpace = containerWidth - itemWidthCount - 5; // minus five is to avoid issues with slight differnces between browser's calculations.
	var itemPadding = Math.floor((freeSpace / itemCount)/2);
	containerItems.each(function() {
		var leftPadding = parseInt($(this).css("padding-left")) + itemPadding + "px";
		var rightPadding = parseInt($(this).css("padding-right")) + itemPadding + "px";
		$(this).css({"padding-left": leftPadding,"padding-right": rightPadding });
	});
}

function countItemsWidth(items) {
	var itemWidthCount = 0;
    items.each(function() {
    	itemWidthCount += $(this).outerWidth();
    });
    return itemWidthCount;
}

function prepopulateFromTitle(selector) {	
	var inputs = $(selector);
	inputs.each(function() {				
		if($(this).attr("value") == "") {
			if ($(this).attr("type") == "password") {				
				var id = $(this).attr("id");
				var title = $(this).attr("title");
				var name = $(this).attr("name");
				var value = $(this).attr("title");
				var classStr = $(this).attr("class");
				$(this).replaceWith("<input type='text' class='dynamic " + $(this).attr("class") + "' id='" + $(this).attr("id") + 
				"' name='" + $(this).attr("name") + "' value='" + $(this).attr("title") + "' title='" + $(this).attr("title") + "'  />");				
			} else { 
				$(this).val($(this).attr("title"));
			};
		};				
		$(this).focus(function() {
			if ((!($(this).attr("type") == "password") && ($(this).attr("value") == $(this).attr("title")))) {				
				$(this).val("");
			};			
		});		
		$(this).blur(function() {			
			if ((!($(this).attr("type") == "password") && ($(this).attr("value") == ""))) {											
				$(this).val($(this).attr("title"));	
			};
		});		
	});	
	$("input[type*='text']").live("focus", function() {		
		clascToLook = $(this).attr("class").toString();
		if (clascToLook.match(/dynamic/)) {
			if ($(this).attr("value") == $(this).attr("title")) {			
				$(this).removeClass("dynamic");
				var id = $(this).attr("id");
				var title = $(this).attr("title");
				var name = $(this).attr("name");
				var classStr = $(this).attr("class");			
				$(this).replaceWith("<input type='password' class='" + $(this).attr("class") + "' id='" + $(this).attr("id") + 
				"' name='" + $(this).attr("name") + "' value='' title='" + $(this).attr("title") + "' />");
				setTimeout( function() {
					$("#" + id).focus();
				} , 500); // setTimeout used because IE7 needs a bit of time to execute focus
			};
		};
	});
	$("input[type*='password']").live("blur", function() {
		if ($(this).attr("value") == "") {		
			var id = $(this).attr("id");
			var title = $(this).attr("title");
			var name = $(this).attr("name");
			var value = $(this).attr("value");
			var classStr = $(this).attr("class");	
			$(this).replaceWith("<input type='text' class='dynamic " + $(this).attr("class") + "' id='" + $(this).attr("id") + 
			"' name='" + $(this).attr("name") + "' value='" + $(this).attr("title") + "' title='" + $(this).attr("title") + "' />");
		};
	});
}

function preopulateInput(selector, value) {
	var field = $(selector);
	var currentValue = field.val();
	if (currentValue == "") {
		field.val(value);
	};
	field.focus(function() {
		currentValue = field.val();
		if (currentValue == value) {
			field.val("");
		}
	});
	field.blur(function() {
		currentValue = field.val();
		if (currentValue == "") {
			field.val(value);
		};
	});
};

function showFieldBasedOnValue(formElemWithText, requiredText, formElemToShowSelector) {
	showHide();
	$(formElemWithText).change(function() {
		showHide();
	});
	function showHide() {
		var input = $(formElemWithText);
		if (input.length !== 0) {
			var selIndex = input[0].selectedIndex;
			var selText = input.find(":nth-child("+ (selIndex + 1) +")").text();
			if (selText == requiredText) {
				$(formElemToShowSelector).parent().show();
			} else {
				$(formElemToShowSelector).parent().hide();
			}
		}
	}
}
$(document).ready(function() {
	var searchWritten = false;
	if($(".relatedContents").find(".manual").length <= 0){
		$(".relatedContents").find("ul").find("li").each(function (i) { $(this).removeClass("firstAuto");});

	}
	var simpleTitle = $(".simple").find(".header").find("h5").html();
	$(".simple").find(".content").find("ul").prepend("<li class='holderTitle' style:visibility='hidden'>"+simpleTitle+"<li>");
	
// Commented out for MLB-19	
//	$("#idReasonVisit").change(function(){
//		if($(this).val() != "Other (please specify below)"){
//			$("#idOtherReasonVisit").val("");
//		}
//		
//	});
	
	$(".simpleSearch").find(".button").click(function(){
		if(searchWritten != true){
			$("input[name=searchString]").val("");}
		});
	$("input[name=searchString]").keydown(function(){searchWritten = true;});

	$("input[name=searchString]").blur( function(){
		if(searchWritten != true){
		if($("input[name=searchString]").val()=="Search"){
			$("input[name=searchString]").val("");}}
		
	} );
	
});
