var newWindow = null;
function closeWin(){
	if (newWindow != null){
		if(!newWindow.closed)
			newWindow.close();
	}
}

function popUpWin(url, type, strWidth, strHeight){
	closeWin();
	if (type == "fullScreen"){
		strWidth = screen.availWidth - 10;
		strHeight = screen.availHeight - 160;
	}
	var tools="";
	if (type == "standard" || type == "fullScreen") tools = "resizable,toolbar=no,location=no,scrollbars=yes,menubar=no,width="+strWidth+",height="+strHeight+",top=0,left=0";
	if (type == "console") tools = "resizable,toolbar=no,location=no,scrollbars=yes,width="+strWidth+",height="+strHeight+",left=0,top=0";
	newWindow = window.open(url, 'newWin', tools);
	newWindow.focus();
}

function ShowSection(parentElement, selectedElement)
{
	alert(parentElement + " " + selectedElement.value);
	
	// hide all child div's inside section_area div 
	$("#" + parentElement +" > div").hide();	
	// show the element	
	$("#" + selectedElement.value).show();
	
}

function decrypt_string(crypted_string) {

	var numbers = crypted_string.split(' ');			
	n = numbers[0];	decryption_key = numbers[1];			
	numbers[0] = ""; numbers[1] = "";				
	crypted_string = numbers.join(" ").substr(2);


	var decrypted_string = '';
	var crypted_characters = crypted_string.split(' ');
	var i;
	
	for(i = 0; i< crypted_characters.length; i++) {
		var current_character = crypted_characters[i];
		var decrypted_character = exponentialModulo(current_character,n,decryption_key);
		decrypted_string += String.fromCharCode(decrypted_character);
	}
	
	return decrypted_string;
}

// Finds base^exponent % y for large values of (base^exponent)
function exponentialModulo(base,exponent,y) {
	if (y % 2 == 0) {
		answer = 1;
		for(var i = 1; i <= y/2; i++) {
			temp = (base*base) % exponent;
			answer = (temp*answer) % exponent;
		}
	} else {
		answer = base;
		for(var i = 1; i <= y/2; i++) {
			temp = (base*base) % exponent;
			answer = (temp*answer) % exponent;
		}
	}
	return answer;
}

function sendEmail(dat)
{
    document.location.href='mailto:' + do_decrypt ( dat );
}

function do_decrypt(dat)
{ 
	return decrypt_string ( dat, 0, 0 ,'');
}

function isNumberKey(evt) {
    //stop event bubbling
    if (!evt) var evt = window.event;
    evt.cancelBubble = true;
    if (evt.stopPropagation) evt.stopPropagation();

    try {
        var charCode = (evt.which) ? evt.which : event.keyCode;
    }

    catch (err)
         { }

    if (charCode == 13) {
        return true;
    }

    else if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }

    return true;
}

function isAlphaNumeric(evt) {
    //stop event bubbling
    if (!evt) var evt = window.event;
    evt.cancelBubble = true;
    if (evt.stopPropagation) evt.stopPropagation();

    try {
        var charCode = (evt.which) ? evt.which : event.keyCode;
    }

    catch (err)
         { }

    if (charCode == 13 || charCode== 32) {
        return true;
    }

    else if ((charCode > 31 && charCode < 48) || (charCode > 57 && charCode <64) ||
              (charCode <97 && charCode > 90) || charCode >122) {
        return false;
    }

    return true;
}

function DeleteWarning(msg) {
    var flg = confirm('Are you sure you want to ' + msg + '\n\nClick OK to continue. Otherwise click Cancel.\n');
    if (flg) return true;
    return false; 
}

function gup(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);

    if (results == null) {
        return "";
    }

    else {
        return results[1];
    }
}

var isLoggedOut = false;
var logoutObj;
var logoutClientId;

function LogoutUser(obj) {
    if (logoutObj == obj && isLoggedOut) {
        return true;
    } else if (logoutObj && logoutObj != obj) {
        __doPostBack('ctl00$ctl00$RecognizedLoginStatus1$ctl00', '');
        return true;
    }
    if (obj)
        logoutObj = obj;

    isLoggedOut = true;
    $.ajax({
        type: "POST",
        url: "/Selfserve.Cca/webservices.asmx/IsBasketEmpty",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
        if (msg.d.toString() == 'true') {
            __doPostBack('ctl00$ctl00$RecognizedLoginStatus1$ctl00', '');
            } else {
                $.nyroModalManual({
                    url: '#cartItems',
                    minWidth: 450, // Minimum width
                    minHeight: 200, // Minimum height
                    height: 200,
                    type: 'div',
                    width: 450,
                    modal: true
                })
            }
        }
    });
    return false;
}

function KillLogout() {
    logoutObj = null;
}

function SetDefaultSearchKeywords(obj) {
    var defaultKeyword = "Search mycca product catalogue";
    if (obj.value == defaultKeyword) {
        obj.value = '';
    }
    else if (obj.value == '') {
        obj.value = defaultKeyword;
    }
}
 
function SetSearchKeywords(name, obj)
{
    var searchText = "";
    var searchTextArray = $("[id$='_SearchTextBox']"); 
    
    $.query.EMPTY();
    
    if (name == "mainSearch")
    {
        searchText = searchTextArray[1].value; 
    } 
    else if (name == "topSearch" || name == "topSearchHidden")
    {
        searchText = searchTextArray[0].value; 
    }
    
    if (searchText != "") 
    {
        $.query.SET('searchkeywords', searchText);  
    }
    
    var queryString = $.query.toString(); 
 
    if (name == "mainSearch")
    { 
        $("form")[0].action = "/SelfServe.Cca/Search.aspx" + queryString;
    } 
    else if (name == "topSearch")
    {
        obj.href = obj.href.replace('Search.aspx','Search.aspx' + queryString);
    }
    else if (name == "topSearchHidden")
    {     
        WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(obj.name, "", false, "", "/SelfServe.Cca/Search.aspx" + queryString, false, true));
    } 
    
    return;
}

function scroll() {
    scrollTo(0, 0);
}

$(document).ready(function() {

    // show/hide specials
    $(".show-specials a").click(function() {
        $(this).parent()
            .find('ul').show();
        $(this).hide();
        return false;
    });
    $(".show-specials ul li").click(function() {
        $(this).parent()
            .hide()
            .parent().find('a').show();
          
    });

    // show/hide info   big
    $(".info-container a.show-info").hover(function(e) {
        $("#primary-nav").css("z-index", 1); // this is to ensure that the info container always appears on top of the navigation.  This, unfortunately, inactivates the drop down list for the nav.
        var isBig = $(this).parent().find('.info-content.big').length > 0;
        var isMedium = $(this).parent().find('.info-content.medium').length > 0;
        var isSmall = $(this).parent().find('.info-content.small').length > 0;
        $(this).parent().find('.info-content').clone().appendTo($('body'));
        var positionChange = isBig ? 145 : isMedium ? 115 : 85;
        var xAndY = 'position:absolute;display:block;top:' + (e.pageY - positionChange) + 'px;left:' + e.pageX + 'px;z-index:100;';
        $('body > .info-content').attr('style', xAndY);
        $("#content").css("overflow", "visible");
    }, function() {
        $("#primary-nav").css("z-index", 50); // reset the z-index value for primary-nav
        $('body > .info-content').remove();
        $("#content").css("overflow", "hidden");
    });
    //Hide (Collapse) the toggle containers on load
    $(".toggle_container").hide();

    //Switch the "Open" and "Close" state per click
    $("h2.trigger").toggle(function() {
        $(this).addClass("active");
    }, function() {
        $(this).removeClass("active");
    });

    //Slide up and down on click
    $("h2.trigger").click(function() {
        $(this).next(".toggle_container").slideToggle("slow");
    });
});
