/* jQuery functions */

(function($)
{
   $.fn.showHtml = function(html, speed, callback)
   {
	  this.each(function()
	  {
		 var el = $(this);
		 var finish = {width: this.style.width, height: this.style.height};
		 var cur = {width: el.width()+'px', height: el.height()+'px'};

		 el.html(html);

		 var next = {width: el.width()+'px', height: el.height()+'px'};

		 el .css(cur)
			.animate(next, speed, function() 
			{
			   el.css(finish);
			   if ( $.isFunction(callback) ) callback();
			});
	  });
   };


})(jQuery);

(function($)
{
   $.fn.switchDiv = function(oldDiv, newDiv, speed, callback)
   {
	  this.each(function()
	  {
		 var el = $(this);
		 var oDiv = $(oldDiv);
		 var nDiv = $(newDiv);
		 var finish = {width: this.style.width, height: this.style.height};
		 var cur = {width: el.width()+'px', height: el.height()+'px'};

		 oDiv.hide();
		 nDiv.show();

		 var next = {width: el.width()+'px', height: el.height()+'px'};

		 el .css(cur)
			.animate(next, speed, function() 
			{
			   el.css(finish);
			   if ( $.isFunction(callback) ) callback();
			});
	  });
   };


})(jQuery);

(function($){  
$.fn.constrainInput = function(config){  
   var settings = $.extend({  
	  allowedCharsRegex: ".*"  
   }, config);  
	  var re = new RegExp(settings.allowedCharsRegex);  
   $.each(this, function(){  
	 var input = $(this);  
	  
	 var keypressEvent = function(e){  
	   e= e || window.event;  
	   var k = e.charCode || e.keyCode || e.which;  
	   if(e.ctrlKey || e.altKey || k == 8){//Ignore  
		 return true;  
	   } else if ((k >= 41 && k <= 122) ||k == 32 || k > 186){//typeable characters  
		 return (re.test(String.fromCharCode(k)));  
	   }  
	   return false;  
	 }  
	 input.bind("keypress",keypressEvent);  
   });  
   return this;  
 };  
$.fn.wait = function(time, type) {
        time = time || 1000;
        type = type || "fx";
        return this.queue(type, function() {
            var self = this;
            setTimeout(function() {
                $(self).dequeue();
            }, time);
        });
};
})(jQuery);

/* Input filtering/masking */

jQuery(function($){
	$("#inputFilterDomain").constrainInput({allowedCharsRegex: "[a-z0-9-æøåöäë]"});
});

/* jQuery triggers when DOM loaded */

$(document).ready(function(){

	$("#myispLoginForm").validate({
		success: function(label) {
			label.html("&nbsp;").addClass("valid");
		},
		rules: {
			myisppassword: {
				required: true,
				minlength: 5
			}
		}
	});
	
	$("#myispForgotPassword").click(function () { 
		window.location = "https://www.myisp.no/cmd/forgotpassword";
	});
	
	$("#webmailloginlink").click(function () { 
		window.location = "http://www.mywebmail.no/";
	});
	
	$("#frontdomainlink").click(function () { 
		window.location = "http://www.mywebhost.no/domener/";
	});
	
    $("input:text").focus(function () {
		$(this).toggleClass("focus");
    });	
	
	$("input:text").blur(function () {
		$(this).removeClass("focus");
    });
    
    $("input:password").focus(function () {
		$(this).toggleClass("focus");
    });	
	
	$("input:password").blur(function () {
		$(this).removeClass("focus");
    });
	
	$("#sitesearch").click(function () {
		document.googlesearch.submit();
    });
    
    swapValues = [];
    $(".swap_value").each(function(i){
        swapValues[i] = $(this).val();
        $(this).focus(function(){
            if ($(this).val() == swapValues[i]) {
                $(this).val("");
				$(this).css("color","#333333");
            }
        }).blur(function(){
            if ($.trim($(this).val()) == "") {
                $(this).val(swapValues[i]);
                $(this).css("color","#cccccc");
            }
        });
    });
    
    $.getJSON("https://www.myisp.no/cmd/login_chk?rtype=json&callback=?",{}, function(answer){
		if (answer["loggedin"] == true) {
			$("#whoamihtml").html(answer["loggedin_text"] + " " + answer["customerno"] + " - " + answer["name"] + '&nbsp;<a href="https://www.myisp.no/cmd/logout" class="myisplogoutlink">[ ' + answer["logout_text"] + ' ]</a>');
			if (window.location.hostname == "www.myisp.no") {
				if (window.location.pathname.substring(0,10) == "/cmd/order" && window.location.pathname.substring(0,11) != "/cmd/orders") {
					$("#myisploginlinkhtml").html('<a href="https://www.myisp.no/" class="topmenulink">MyISP</a>');
				}
				else {
					$("#myisploginlinkhtml").html('<a href="https://www.myisp.no/" class="topmenulink-selected">MyISP</a>');
				}
			}
			else {
				$("#myisploginlinkhtml").html('<a href="https://www.myisp.no/" class="topmenulink">MyISP</a>');
			}
		}
    } );
	
	$.fn.qtip.styles.myTooltip = {
	   background: '#900000',
	   color: '#ffffff',
	   textAlign: 'center',
	   padding: 2,
	   border: {
		  width: 5,
		  radius: 5,
		  color: '#900000'
	   },
	   tip: 'bottomLeft',
	   name: 'cream' // Inherit the rest of the attributes from the preset dark style
	}
	$.fn.qtip.styles.myCompareTooltip = {
	   background: '#900000',
	   color: '#ffffff',
	   textAlign: 'center',
	   padding: 2,
	   border: {
		  width: 5,
		  radius: 5,
		  color: '#900000'
	   },
	   tip: 'bottomMiddle',
	   name: 'cream' // Inherit the rest of the attributes from the preset dark style
	}

	$('.front-content-top-links a[title]').qtip({ style: { name: 'myTooltip', tip: true }, position: { corner: { target: 'bottomMiddle', tooltip: 'topLeft' } } })
	$('.topmenulink-front').qtip({ style: { name: 'myTooltip', tip: true }, position: { corner: { target: 'bottomMiddle', tooltip: 'topLeft' } } })
	$('#searchbox').qtip({ style: { name: 'myTooltip', tip: true }, position: { corner: { target: 'topMiddle', tooltip: 'bottomLeft' } } })
	$('#searchbox-index').qtip({ style: { name: 'myTooltip', tip: true }, position: { corner: { target: 'bottomMiddle', tooltip: 'topLeft' } } })
	$('.document-link[title]').qtip({ style: { name: 'myTooltip', tip: true }, position: { corner: { target: 'topMiddle', tooltip: 'bottomLeft' } } })
	$('img[title]').qtip({ style: { name: 'myTooltip', tip: true }, position: { corner: { target: 'topMiddle', tooltip: 'bottomLeft' } } })
	$('td[title]').qtip({ style: { name: 'myCompareTooltip', tip: { size: { x: 18, y: 10 } } }, position: { corner: { target: 'topMiddle', tooltip: 'bottomMiddle' } } })
	
});

/* JS handlers */

popupStatus = 0;

function myispLogin() {
	$("#myispLoginFormError").hide();
	if ($("#myispLoginForm").valid() == true) {
		var username=$("#myispusername").val();
		var password=$("#myisppassword").val();
		$.getJSON("https://www.myisp.no/cmd/login?rtype=json&callback=?",{username:username, password:password}, function(answer){ 
			if (answer[0] == true) {
				$("#myispLoginFormConfirm").html(answer[1]);
				$("#myispLoginFormConfirm").show();
				window.location = "https://www.myisp.no/";
			}
			else {
				$("#myispLoginForm").resetForm();
				$("#myispLoginFormError").html(answer[1]);
				$("#myispLoginFormError").show();
			}
		} );
	}
}

function showDomainSearch() {
	$("#DomainSearchError").hide();
	$("#contentDomainSearchContainer").switchDiv("#contentDomainSearchList", "#contentDomainSearchBox");
}

function doDomainSearch() {
	var tlds = new Array()
		tlds[0] = "no"
		tlds[1] = "com"
		tlds[2] = "net"
		tlds[3] = "org"
		tlds[4] = "info"
		tlds[5] = "biz"
		tlds[6] = "name"
		tlds[7] = "cc"
		tlds[8] = "tv"
		
	var newhtml = new String()
	var searchDomainTxt = $("#inputFilterDomain").val();
	var searchDomainTxtLen = searchDomainTxt.length;
	var searchDomainOutput = $("#contentDomainSearchList");
	
	if (searchDomainTxtLen <= 1)
	{
		$("#DomainSearchError").show();
		return;
	}

	newhtml = newhtml + '<div class="contentDomainSearchContainer">'	
	for(i=0;i<tlds.length;i++) {
		newhtml = newhtml + '<div class="contentDomainSearchDomain" id="searchdomain' + tlds[i] + '">' + searchDomainTxt + '.' + tlds[i] + '</div><div class="contentDomainSearchLoading" id="searchdomain' + tlds[i] + 'status"><img src="https://images.mywebhost.no/5/ajax-loader-leftmenu.gif" alt="Laster..." width="16" height="16"></div>'
	}
	newhtml = newhtml  + '&nbsp;</div>Bestilling gj&oslash;res ved &aring; klikke p&aring; domenet. For &aring; flytte et domene til MyWebhost, <a href="https://www.myisp.no/cmd/order?mode=transfer">klikk her</a>.<br /><br/><div class="buttons"><button type="button" onClick="javascript:showDomainSearch();"><img src="https://images.mywebhost.no/5/icon-search.png" alt="" width="16" height="16" />Nytt søk</button></div>'

	searchDomainOutput.html(newhtml);
	$("#contentDomainSearchContainer").switchDiv("#contentDomainSearchBox", "#contentDomainSearchList");
	
	/* Domain lookup */
	for(i=0;i<tlds.length;i++) {
		$.ajaxSetup({
		  timeout: 10000,
		  dataType: "jsonp",
		  error: function(ErrorRequest, ErrorTextStatus, ErrorThrown){
					doDomainSearchUpdateFailure(tlds[i]);
				}
		});
		$.getJSON("https://www.myisp.no/whois/?funckey=asdfmnl123978645k23lk4jmnbsdfnpio1367889sy9123haljksdsajdghbmyufry76t1256r2398&lang=no_NO&domain=" +searchDomainTxt+ "&tld=" +tlds[i]+ "&callback=?",{},doDomainSearchUpdate);
	}
}

function doDomainSearchUpdate(answer) {
	if (answer["available"] == "true") {
		$("#searchdomain"+answer["tld"]).html('<a href="https://www.myisp.no/cmd/order?domain='+answer["domain2"]+'&check_id='+answer["check_id"]+'">' +answer["domain"]+ '</a>');
		$("#searchdomain"+answer["tld"]+"status").html('<img src="https://images.mywebhost.no/5/icon-tick.png" alt="Ledig!" width="16" height="16">');
	}
	else if (answer["available"] == "false") {
		$("#searchdomain"+answer["tld"]+"status").html('<img src="https://images.mywebhost.no/5/icon-cross.png" alt="Opptatt" width="16" height="16">');
	}
	else {
		doDomainSearchUpdateFailure(answer["tld"]);
	}
}

function doDomainSearchUpdateFailure(tld) {
	$("#searchdomain"+tld+"status").html('<img src="https://images.mywebhost.no/5/icon-warning.png" alt="Ukjent status" width="16" height="16">');	
}

function button_disable(button) {
	$(button).attr('disabled', 'disabled');
	$(button).addClass('disabled');
	$(button).stop().animate({ opacity: 0.5 }, 0);
}

function button_enable(button) {
	$(button).attr('disabled', '');
	$(button).removeClass('disabled');
	$(button).stop().animate({ opacity: 1.0 }, 0);
}

function modal_close() {
	$.modal.close();
}