﻿function SetUniqueRadioButton(nameregex, current) {
	re = new RegExp(nameregex);
	for (i = 0; i < document.forms[0].elements.length; i++) {
		elm = document.forms[0].elements[i]
		if (elm.type == 'radio') {
			if (re.test(elm.name)) {
				elm.checked = false;
			}
		}
	}
	current.checked = true;
}

function detectCapsLock(keyPressEvent, warningElementId) {
	kc = keyPressEvent.keyCode ? keyPressEvent.keyCode : keyPressEvent.which;
	sk = keyPressEvent.shiftKey ? keyPressEvent.shiftKey : ((kc == 16) ? true : false);
	if (((kc >= 65 && kc <= 90) && !sk) || ((kc >= 97 && kc <= 122) && sk))
		document.getElementById(warningElementId).style.display = 'block';
	else
		document.getElementById(warningElementId).style.display = 'none';
}

function fnMouseOver(id) {
	var plain = document.getElementById(id + 'Plain');
	plain.style.display = 'none';
	var rollover = document.getElementById(id + 'Rollover');
	rollover.style.display = 'block';
}

function fnMouseOut(id) {
	var plain = document.getElementById(id + 'Plain');
	plain.style.display = 'block';
	var rollover = document.getElementById(id + 'Rollover');
	rollover.style.display = 'none';
}

/* Like story */
function LikeStory(storyId) {
	var webMethod = '/WebServices/MyPetOnline.asmx/LikeStory'
	var data = "{'storyId':'" + storyId + "'}"

	$.ajax({
		type: "POST",
		url: webMethod,
		data: data,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function (returnCode) {

			var response = returnCode;

			if (response.d == 1) {
				$("#LikeText").text("You liked this story");
				$("#CustomersLike").text("1 person like this");
				$("#LikeImage").attr("src", "/images/UserControls/MyPetNames/paw_dark.png");
			}
			else if (response.d > 1) {
				var votes = response.d;
				$("#LikeText").text("You liked this story");
				$("#CustomersLike").text(votes + " people like this");
				$("#LikeImage").attr("src", "/images/UserControls/MyPetNames/paw_dark.png");
			}
			else {
				$(".UCMyPetStoryLogin").css("visibility", "visible");
			}
		},
		error: function (e) { alert('There was a problem adding your vote.') }
	});

	return true;
}

// Like my pet story function

$(function () {

	var wrapper = $(".UCMyPetStoryContent");
	wrapper.delegate("a", "click", function (e) {

		//Get the clicked item
		var target = $(e.target);

		//Get the class information which is being used to store our SKU attribute
		var storyId = target.attr('class');

		//Check to see if we get a match for a SKU
		if (storyId.startsWith('StoryId')) {
			storyId = storyId.replace("StoryId-", "");
			LikeStory(storyId);
		}
	});

});

function AddToBasket(sku, quantity, redirectToBasket) {

	// ensure quantity is an integer
	quantity = parseInt(quantity);

	//alert(quantity);  // debugging

	if (isNaN(quantity) || quantity <= 0) { quantity = 1; }

	var webMethod = '/Webservices/Basket.asmx/AddQuantityToBasket';
	var data = "{'sku':'" + sku + "' , 'quantity':'" + quantity + "'}";

	//alert(data);  // debugging

	$.ajax({
		type: "POST",
		url: webMethod,
		data: data,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function (message) {
			if (redirectToBasket == true) {
				RedirectToBasket();
			}
			else {
				__doPostBack('UdpBasket', 'customPostback');
			}

		},
		error: function (e) { alert(e) }
	});

	return false;
}

function AddRepeatToBasket(sku, quantity, skuRepeatOptionId, redirectToBasket) {

    // ensure quantity is an integer
    quantity = parseInt(quantity);

    //alert(quantity);  // debugging

    if (isNaN(quantity) || quantity <= 0) { quantity = 1; }

    var webMethod = '/Webservices/Basket.asmx/AddRepeatToBasket';
    var data = "{'sku':'" + sku + "' , 'quantity':'" + quantity + "', 'skuRepeatOptionId':'" + skuRepeatOptionId + "'}";

    //alert(data);  // debugging

    $.ajax({
        type: "POST",
        url: webMethod,
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (message) {
            if (redirectToBasket == true) {
                RedirectToBasket();
            }
            else {
                __doPostBack('UdpBasket', 'customPostback');
            }

        },
        error: function (e) { alert(e) }
    });

    return false;
}



function RedirectToBasket() {
	window.location = "/basket.aspx";
}


// ATB from ATBPanel

$(function () {

	var wrapper = $("body");
	wrapper.delegate("input.addToBasketButton", "click", function (e) {

		//Get the clicked item
		var sender = $(e.target);

		// Traverse UP the DOM to the level just above the radio buttons
		var outerDiv = $(sender).parents(".addToBasketPanel");

		var sku = $(outerDiv).find("input:radio:checked").val();
		var qty = $(outerDiv).find("input.qty").val();

		AddToBasket(sku, qty, true);

	});

});

/* SEARCH POPUP FUNCTIONALITY */

var searchPopupDisabled = false;

function escapeTerm(term) {
	var returnStr = "";
	if (term != undefined && term.length > 0) {

		for (var i = 0; i < term.length; i++) {

			var char = term.charAt(i);

			// define all the characters that should be escaped.
			if (char == '\\' || char == '\'' || char == '\"') {

				returnStr += "\\" + char;
			}
			else {

				returnStr += char;
			}
		}
	}
	return returnStr;
}

function updateSearchQuery(textbox, KEYCODE) {

	var unescapedTerm = textbox.value;
	var term = escapeTerm(unescapedTerm);

	if (searchPopupDisabled) {
		return;
	}

	if (KEYCODE == 27 || term.length < 3) {
		//Hide the popup until 3 characters are entered in to the search box
		hidePopup();
	}
	else {
		// Access SearchSuggestions web method using the current typed search entry

		var resultsReturned = 10;
		var searchTerm = term.toLowerCase();
		var webMethod = '/Webservices/search.asmx/SearchSuggestions';
		var dataIn = "{ searchTerm: '" + searchTerm + "', resultsReturned: '" + resultsReturned + "'}";

		$.ajax({
			type: "POST",
			url: webMethod,
			data: dataIn,
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (data) {

				var htmlReturn = '';
				var result = data.d;
				
				$.each(result, function () {
					htmlReturn += "<li><a href='" + this.Hyperlink + "'>" + this.Text + "</a></li>";
				});

				$('#SugSearchContent').html("<ul>" + htmlReturn + "</ul>");

				highlightTerm($("#SugSearchContent"), searchTerm);

				//Display the popup if the search has a return
				if (htmlReturn != '') {
					$('#SugSearchWrapper').show(200);
				}
				else {
					hidePopup();
				}
			},
			error: function (xmlHttpRequest, statusText, error) {
				if (xmlHttpRequest.status != 0) {
					alert('There was a problem with your search.\n\n' + xmlHttpRequest.status + ' - ' + xmlHttpRequest.statusText + "\n\nStatus Text: " + statusText);
				}
			}

		});
	}
}

function closePopupSearch() {
	searchPopupDisabled = true; // disable it for as long as this JS has scope
	hidePopup();
}

function hidePopup() {
	$('#SugSearchWrapper').hide();
	$('#SugSearchContent').empty();
}

var highlightTerm = function (jQueryElements, terms) {
	var wrapper = ">$1<b style='font-weight:normal;color:#000;background-color:#CFE9FF'>$2</b>$3<";
	for (var i = 0; i < terms.length; i++) {
		var regex = new RegExp(">([^<]*)?(" + terms + ")([^>]*)?<", "ig");
		jQueryElements.each(function (i) {
			$(this).html($(this).html().replace(regex, wrapper));
		});
	};
}

function CheckFileExtension(source, arguments) {
	var sFile = arguments.Value;
	arguments.IsValid =
	((sFile.match(/\.jpg?g$/i)) || (sFile.match(/\.png$/i)) ||
	(sFile.match(/\.PNG$/i)) || (sFile.match(/\.jpeg$/i)) ||
	(sFile.match(/\.JPEG$/i)) || (sFile.match(/\.gif$/i)) ||
	(sFile.match(/\.GIF$/i)) || (sFile.match(/\.JPG?f$/i)));
}

//sender is the object triggering popup.
//popupSelector is the target item (ie: the div to popup with a jquery selector)
//closeOnMaskClick is close on page click (true or false)
function showPopup(sender, popupSelector, closeOnMaskClick) {

	var modal = $(popupSelector);

	// debug
	//alert('doc height:' + $(document).height() + '\nwin height:' + $(window).height() + '\ndoc width:' + $(document).width() + '\nwin width:' + $(window).width() + '\nwin top:' + $(window).scrollTop());

	//Get the screen height and width
	var maskHeight = $(document).height();
	var maskWidth = $(window).width();

	//Set height and width to mask to fill up the whole screen
	$('#mask').css({ 'width': maskWidth, 'height': maskHeight });

	//transition effect for mask
	$('#mask').fadeTo(0, 0.8);

	//Get the pop up width and position the element centrally
	$(modal).css('top', ($(window).height() / 2 - $(modal).height() / 2) + $(window).scrollTop());
	$(modal).css('left', ($(window).width() - $(modal).width()) / 2);

	//Transition effect for pop up window
	$(modal).fadeIn(100);

	if (closeOnMaskClick) {
		//if mask is clicked   
		$('#mask').click(function () {
			$(this).hide();
			$(modal).hide();
		});
	}
}

function hidePopup(sender) {

	var modal = $(sender).closest(".generic-popup");

	$(modal).hide();
	$('#mask').hide();
}


/* Add Event deleage to handle clicking the any button that has the 'close-popup' class */
$(function () {
	$("input.close-popup").click(function (e) {

		hidePopup($(e.target));

	});
});

$(function showThrobber() {
	$('#photo-throbber').append('<img src="/images/MyPetOnline/ajax-loader.gif"/>');
});

/* Moving boxes JS */

$(function () {
    var startPanel = 5;
    if (document.getElementById('StartPosition') != null && document.getElementById('StartPosition').value != "") {
        startPanel = document.getElementById('StartPosition').value;}

    $('#slider').movingBoxes({
        startPanel: startPanel,      // start with this panel
        width: 945,    // overall width of movingBoxes (not including navigation arrows)
        panelWidth: .17,     // current panel width adjusted to 70% of overall width
        reducedSize: 0.75,
        disabled: '',
        fixedHeight: true,
        buildNav: true,   // if true, navigation links will be added
        navFormatter: function (index, panel) { return panel.find('h2 span').text(); }, // function which gets nav text from span inside the panel header
        completed: function (e, slider, tar) {
            var currentProductId = $(".current").attr("id");
            // specify that we do not want the following to be cached
            $.ajaxSettings.cache = false;

            // set up variable for url of repeat options panel
            var urlToload = String(window.parent.document.location);
            urlToload = urlToload.substring(0, urlToload.indexOf('/', 14)) + '/repeatorder/repeatoptionspanel/' + currentProductId;

            // reload contents of div from the MVC URL
            $('#repeat-options').load(urlToload);
            $('#repeat-options-info').html("");
        }
    });
});

function UpdateRepeatInfoPanel(currentRepeatSkuId) {
    
    if (currentRepeatSkuId == 0) {
        // Don't try and reload the panel because the customer has selected the "select an option" index in the dropdown
    }
    else {
        // specify that we do not want the following to be cached
        $.ajaxSettings.cache = false;

        // set up variable for url of repeat options info panel
        var urlToload = String(window.parent.document.location);
        urlToload = urlToload.substring(0, urlToload.indexOf('/', 14)) + '/repeatorder/repeatoptionsinfopanel/' + currentRepeatSkuId;

        // reload contents of div from the MVC URL
        $('#repeat-options-info').load(urlToload);
    }
};
