$.fn.hrefId = function() { return $(this).attr('href').substr($(this).attr('href').indexOf('#') + 1); };
$.fn.hrefTarget = function() { return $('#' + $(this).hrefId()); };
$.fn.hrefClassTarget = function($elem) { return $elem.find('.' + $(this)); };


$('.js .panes > div').hide();
$('.js .panes > div:first-child').show();
$('.js .vertical-accordion li p').hide();
$('.js .vertical-accordion li:first-child p').show();


/**
 * Tabs changing
 */
$.fn.tabs = function() {
    return this.each(function() {
		var $tabs = $(this);
        var $liItems = $tabs.find('> div.navigation ul li');
        $liItems.each(function() {
			var $li = $(this);
			$li.find('a').click(function(e) {
				var $a = $(this);

				if ($li.hasClass('active'))
					return;

				if ($a.hasClass('load'))
					return true;
				else
					e.preventDefault();

				$liItems.removeClass('active');
				$liItems.find('a').each(function() {
					$tabs.find('.' + $(this).hrefId()).hide();
				});
				$a.parent().addClass('active');
				$tabs.find('.' + $a.hrefId()).show();
			});
		});

        $(this).find('div.navigation ul li#tab-1 a').click();
    });
};

$('div.tabs, div.alt-tabs').tabs();


/**
 * Vertical simple accordion
 */
$('.js .vertical-accordion li strong').click(function(e) {
	e.preventDefault();
	var $strong = $(this);
	if ($strong.siblings('p').is(':visible'))
		return;
	$('.js .vertical-accordion li p').each(function(i) {
		if ($(this).is(':visible'))
			$(this).slideUp(100);
	});
	$strong.siblings('p').slideDown(100);
});

/**
 * nadpisuje funkcję val() dla całego jQuery, nie tylko dla pojedynczych obiektów. Ma to dwie pozytywne konsekwencje:
 * 1. Pobranie wartości przy użyciu innego selektora zachowuje się teraz tak, jak byśmy tego oczekiwali
 * 2. Nie mamy n kopii tej samej funkcji w pamięci
 *
 * http://snippy.merix.local/snippet/uniwersalny-skrypt-do-inputa-z-domyslna-wartoscia/
 */
$.fn._val=$.fn.val;$.fn.val=function(b){if(typeof b!="undefined"){return this._val(b)}var a=this._val();if(!this.is("input")||!this.data("default-value")){return a}return a===this.data("default-value")?"":a};$.fn.defaultVal=function(c,a,b){return this.each(function(){var e=$(this);e.data("default-value",c);if(e.val()===""){e.val(c);if(a){e.addClass(a)}}e.focus(function(){e.val(e.val());if(a){e.removeClass(a)}if(b){e.addClass(b)}}).blur(function(){if(e.val()===""){e.val(c);if(a){e.addClass(a)}if(b){e.removeClass(b)}}});var d=e.closest("form");if(d.length){d.submit(function(){e.val(e.val())})}})};
$('.domain-register input, .domain-search input').defaultVal('Enter your domain name...', 'default');
$('#search-domain #domain-name').defaultVal('enter domain', 'default');
$('#search-ipaddress #domain-name').defaultVal('enter IP address', 'default');

/**
 * Offer countdown timer. Depend on valid Unix Timestamp
 */
function OfferTimer(b, e, c) {
    this.defaultOptions = {id: {days: ".days", hours: ".hours", minutes: ".mins", seconds: ".secs"}};
    var d = $.extend(this.defaultOptions, b);
    this.config = [];
    $.extend(this.config, d);
    this.actualUnixTime = e;
    this.targetUnixTime = c;
    var a = this;
    setInterval(function() {
        a.update()
    }, 1000)
}

OfferTimer.prototype = {
    update: function() {
        var b = this.targetUnixTime - this.actualUnixTime;
        var d = 0;
        if (b > 86400) {
            d = Math.floor(b / 86400);
            b -= d * 86400;
        }
        var a = 0;
        if (b > 3600) {
            a = Math.floor(b / 3600);
            b -= a * 3600;
        }
        var c = 0;
        if (b > 60) {
            c = Math.floor(b / 60);
            b -= c * 60;
        }
        seconds = b;
		$(this.config.id.days).html(d);
        $(this.config.id.hours).html(a);
        $(this.config.id.minutes).html(c > 0 && c < 10 ? '0' + c : c);
        $(this.config.id.seconds).html( seconds > 0 && seconds < 10 ? '0' + seconds : seconds);
        if(a == 0 && c == 0 && seconds == 0) {
            document.location.reload(); // offer finished
        }
        this.targetUnixTime -= 1;
    }
};

/**
 * Usage: OfferTimer(object, current timestamp, target timestamp);
 */

var ts = Math.round((new Date()).getTime() / 1000);
if (expire_time != 'undefined') {
  new OfferTimer({}, ts, expire_time);
  $('.hosting-offer ul.loading').removeClass('loading');
} else if (expire_time == 'undefined') {
  var expire_time;
}


/**
 * Remove Skype phone number formatting
 */
$('span.skype_pnh_print_container').each(function() {
	if(!$('#skype_plugin_object').length) { return; }
	$('#skype_plugin_object').remove();
	$('span.skype_pnh_print_container').each(function() {
		var originalPhone_ = $(this).text();
		//get all the html that is not in print_container or container
		var originalHTML_ = $(this).parent().html();
		$(originalHTML_).find('span.skype_pnh_print_container').replaceWith(originalPhone_);
		$(originalHTML_).remove('span.skype_pnh_container');
		$(this).parent().html($(originalHTML_));
	});
});


/**
 * Movable progressbar
 */
$('.servers li a').each(function() {
	var $a = $(this);
	$a.click(function(e) {
		e.preventDefault();
		xPos = parseInt($(this).parent().prevAll().length);
		$('.servers li').removeClass('active');
		var left = ((xPos) * posWidth) + posWidth/2 - handleOffset;
		$("a.slider-handle").stop(true).animate({left: left}, speed, "swing", slider_update(xPos));
		$(".slider-overlay").animate({width: left + handleWidth/2}, speed, "swing");
		$('#server-' + (xPos + 1)).addClass('active');
	});
});

$(function() {
	$('.servers li:eq(1) a').click();
});

/**
 * changing questions without reloading on home page hosting plan selector
 */
var $hosting_plan_selector = $('.hosting-plan-selector');
var $hosting_plan_selector_links = $('.hosting-plan-selector ul a, ul.hosting-plans a');
var $plan_selector = $('.plan-selector');
var $call_action_button = $('a.call-action-button');
var $restart_button = $('a.restart-button');
var hosting_plan_selector_depth = 0;
var TIME = 200;

var assign_action = function() {
	$hosting_plan_selector_links.each(function() {
		var $a = $(this);
		$a.click(function(e) {
			e.preventDefault();
			if (hosting_plan_selector_depth == 1) {
				$([$call_action_button, $restart_button]).each(function() {
					$(this).fadeIn(TIME);
				});
			}
			hosting_plan_selector_depth++;
			if (!$a.hrefTarget().length) {
				return;
			}
			$('.hosting-plans:visible').fadeOut(TIME, function() {
				$('#' + $a.hrefId()).fadeIn(TIME);
			});
		});
	});
};

assign_action();

$restart_button.click(function(e) {
	// back to main questions
	e.preventDefault();
	hosting_plan_selector_depth = 0;
	$([$call_action_button, $restart_button]).each(function() {
		$(this).hide();
	});
	$('.hosting-plans').each(function() {
		if ($(this).is(':visible'))
			$(this).fadeOut(TIME, function() {
				$('#primary-questions').show();
			});
	});
	//assign_action();
});

/*
 * Custom styled select elements. [@see opendoor.pl]
 */
$.fn.styledSelect = function(s) {
	var size = s;
	var $select = this.addClass('replaced'), $styled = $select.data('$styled');
	var init = function() {
		$select.addClass('replaced');
		var error = $select.hasClass('error') ? ' error' : '';
		var disabled = $select.is(':disabled') ? ' disabled' : '';
		if (s == 'large')
			$styled = $('<span class="styled-select2' + error + disabled + ' ' + $select.attr('class') + '"><span></span></span>').insertAfter($select);
		else if (s == 'lightgray')
			$styled = $('<span class="styled-select3' + error + disabled + ' ' + $select.attr('class') + '"><span></span></span>').insertAfter($select);
		else if (s == 'setup-dropdown')
			$styled = $('<span class="styled-select4' + error + disabled + ' ' + $select.attr('class') + '"><span></span></span>').insertAfter($select);
		else if (s == 'ssl-dropdown')
			$styled = $('<span class="styled-select5' + error + disabled + ' ' + $select.attr('class') + '"><span></span></span>').insertAfter($select);
		else
			$styled = $('<span class="styled-select' + error + disabled + ' ' + $select.attr('class') + '"><span></span></span>').insertAfter($select);
		$select.data('$styled', $styled);
		$styled.mousedown(function(e) {
			if ($(this).hasClass('focus'))
				// Prevent closing opened dropdown.
				e.stopPropagation();
		});

		$styled.click(function(e) {
			if (!$select.data('$dropdown'))
				$select.trigger('focus');
			else
				$.styledSelectCloseAllDropdowns();
		});
		$select.bind('focus', showDropdown);

		// When value of select changes, then change also displayed value in
		// styled select.
		$select.change($select.updateValue);
		$select.updateValue();

		$select.keypress(function(e) {
			$select.updateValue();
			if (e.which == 13 || e.which == 32)
				return false;
		});

		$select.keyup(function(e) {
			$select.updateValue();
			if (e.which == 13 || e.which == 32) {
				$select.trigger('change');
				$.styledSelectCloseAllDropdowns();
			}
		});

		$select.data('styledSelectInitialized', true);
		return $select;
	};

	$select.updateValue = function() {
	   var v = $select.val();
	   $styled.children('span').text($select.find('option[value="' + v + '"]').text());

	   if ($select.data('$dropdown')) {
		   var $active = $select.data('$dropdown').find('a').removeClass('active').filter('[value="' + v + '"]').addClass('active');
		   var pos = $active.position();
		   $active.closest('ul').scrollTop(Math.floor(pos.top + $active.closest('ul').scrollTop()));
	   }

	   return $select;
	};

	$select.disable = function() {
	   $select.attr('disabled', 'disabled');
	   $styled.addClass('disabled');
	   return $select;
	};

	$select.loading = function() {
	   $select.disable();
	   $styled.children('span').html('<img src="' + settings.staticUrl + 'images/loading_1.gif" alt="">&nbsp;');
	   return $select;
	};

	$select.enable = function() {
	   $select.removeAttr('disabled');
	   $styled.removeClass('disabled');
	   return $select;
	};

	$select.setOptions = function(newOptions) {
	   var optionsHtml = '<option value="">' + gettext('---------') + '</option>';
	   for (var i = 0; i < newOptions.length; i++)
		   optionsHtml += '<option value="' + newOptions[i] + '">' + newOptions[i] + '</option>';

	   return $select.html(optionsHtml).updateValue();
	};

	$select.setValue = function(newValue) {
	   return $select.val(newValue).trigger('change');
	};

	var showDropdown = function() {
		if ($select.data('$dropdown') || $select.is(':disabled'))
		   return;

		var $dropdown =  $('<div class="styled-select-dropdown"><ul></ul></div>');
	   $select.children('option').each(function() {
		   var $li = $('<li><a href="#"></a></li>');

		   $li.children('a').text($(this).text()).attr('value', $(this).val()).mousedown(function(e) {
			   e.stopPropagation();
			   $select.val($(this).attr('value'));
			   $select.updateValue();
			   $styled.removeClass('focus');
			   $select.trigger('change');
			   $dropdown.remove();
		   }).click(function(e) { e.preventDefault(); });

		   $li.appendTo($dropdown.children('ul'));
	   });

	   $dropdown.bind('mousedown', function(e) {
		   // Prevent closing opened dropdown.
		   e.stopPropagation();
	   });

	   $dropdown.children('ul').bind('scroll', function(e) {
		   $select.trigger('focus');
	   });

	   $dropdown.css({borderColor: $styled.css('border-color')});

	   var pos = $styled.offset();
	   $dropdown.css({
		   minWidth: ($styled.width() + 20) + 'px',
		   left: pos.left + 'px',
		   top: (pos.top + $styled.outerHeight() - 1) + 'px'
	   }).appendTo('body');

		   $select.data('$dropdown', $dropdown);

		   $styled.addClass('focus');
		   $select.updateValue();
	};

	if (this.length > 1)
		return this.each(function() {
			$(this).styledSelect(size);
		});
	if ($select.data('styledSelectInitialized'))
	   return $select;
	return init();
};

$.styledSelectCloseAllDropdowns = function() {
	$.closeAllDropdowns();
};

$.closeAllDropdowns = function() {
	$('select.replaced').data('$dropdown', null);
	$('body>.styled-select-dropdown').remove();
	$('.styled-select').removeClass('focus');
};

$('input, select, textarea').bind('focus', function() {
	if (!$(this).data('$dropdown'))
		$.styledSelectCloseAllDropdowns();
});

$(document).mousedown($.styledSelectCloseAllDropdowns);
$(window).resize($.styledSelectCloseAllDropdowns);

$('select.tld:not([multiple], .domain-search.home select)').styledSelect();
$('.domain-register select').styledSelect();
$('.domain-search.home select').styledSelect('large');
$('.offer-comparison select').styledSelect('lightgray');
$('.ssl-comparison select').styledSelect('ssl-dropdown');
$('.setup .alt-dropdown').styledSelect('setup-dropdown');

/*
jquery.event.drag.js ~ v1.5 ~ Copyright (c) 2008, Three Dub Media (http://threedubmedia.com)
Liscensed under the MIT License ~ http://threedubmedia.googlecode.com/files/MIT-LICENSE.txt
*/
(function(E){E.fn.drag=function(L,K,J){if(K){this.bind("dragstart",L)}if(J){this.bind("dragend",J)}return !L?this.trigger("drag"):this.bind("drag",K?K:L)};var A=E.event,B=A.special,F=B.drag={not:":input",distance:0,which:1,dragging:false,setup:function(J){J=E.extend({distance:F.distance,which:F.which,not:F.not},J||{});J.distance=I(J.distance);A.add(this,"mousedown",H,J);if(this.attachEvent){this.attachEvent("ondragstart",D)}},teardown:function(){A.remove(this,"mousedown",H);if(this===F.dragging){F.dragging=F.proxy=false}G(this,true);if(this.detachEvent){this.detachEvent("ondragstart",D)}}};B.dragstart=B.dragend={setup:function(){},teardown:function(){}};function H(L){var K=this,J,M=L.data||{};if(M.elem){K=L.dragTarget=M.elem;L.dragProxy=F.proxy||K;L.cursorOffsetX=M.pageX-M.left;L.cursorOffsetY=M.pageY-M.top;L.offsetX=L.pageX-L.cursorOffsetX;L.offsetY=L.pageY-L.cursorOffsetY}else{if(F.dragging||(M.which>0&&L.which!=M.which)||E(L.target).is(M.not)){return }}switch(L.type){case"mousedown":E.extend(M,E(K).offset(),{elem:K,target:L.target,pageX:L.pageX,pageY:L.pageY});A.add(document,"mousemove mouseup",H,M);G(K,false);F.dragging=null;return false;case !F.dragging&&"mousemove":if(I(L.pageX-M.pageX)+I(L.pageY-M.pageY)<M.distance){break}L.target=M.target;J=C(L,"dragstart",K);if(J!==false){F.dragging=K;F.proxy=L.dragProxy=E(J||K)[0]}case"mousemove":if(F.dragging){J=C(L,"drag",K);if(B.drop){B.drop.allowed=(J!==false);B.drop.handler(L)}if(J!==false){break}L.type="mouseup"}case"mouseup":A.remove(document,"mousemove mouseup",H);if(F.dragging){if(B.drop){B.drop.handler(L)}C(L,"dragend",K)}G(K,true);F.dragging=F.proxy=M.elem=false;break}return true}function C(M,K,L){M.type=K;var J=E.event.handle.call(L,M);return J===false?false:J||M.result}function I(J){return Math.pow(J,2)}function D(){return(F.dragging===false)}function G(K,J){if(!K){return }K.unselectable=J?"off":"on";K.onselectstart=function(){return J};if(K.style){K.style.MozUserSelect=J?"":"none"}}})(jQuery);

/*
 * The slider at VPS page
 */
// slider config
var
	speed = 200,
	xPos = 0,
	posWidth = 142,
	posCount = 6,
	handleWidth = $(".slider-handle").width(),
	handleOffset = Math.round(handleWidth / 2),
	sliderWidth = parseInt($(".slider").width()),
	minPos = 0,
	maxPos = posCount * posWidth - handleWidth ;

var titles = ['VZ256', 'VZ512', 'VZ768', 'VZ1024', 'VZ1512', 'VZ2048'];
var widths = [142, 140, 142, 142, 141, 145]

for (i = 0; i < posCount; i++)
	$(".slider-wrapper").append('<a href="#offer-' + (i + 1) + '" class="point" title="' + titles[i] + '" style="width: ' + widths[i] + '">' + i + '</a>');
$(".slider-wrapper").append('<div class="slider-overlay"></div>');

function slider_update(num){
	// change slider-handle title
	$(".slider-handle").html($($("a.point").get(num)).attr("title"));
	// show appropriate form, hide other forms
	$('.vps-selector .offers div.offer').hide().eq(num).show();
}

Math.mid = function(a, b, c) { return Math.max(a, Math.min(b, c)); };

//when the user clicks on the slider bar
$('a.point').click(function(e) {
	e.preventDefault();
	xPos = parseInt($(this).html());
	$('.servers li').removeClass('active');
	var left = ((xPos) * posWidth) + posWidth/2 - handleOffset;
	$("a.slider-handle").stop(true).animate({'left': left}, speed, "swing", slider_update(xPos));
	$(".slider-overlay").animate({width: left + handleWidth/2}, speed, "swing");
	$('#server-' + (xPos + 1)).addClass('active');
});

//clicking on the slider handle does nothing
$("a.slider-handle").click(function(e){
	e.preventDefault()}
);

//dragging the handle
$("a.slider-handle").drag(function(e){
	xval = e.offsetX - Math.max(0, $("body").width() - sliderWidth) / 2;
	left = Math.mid(minPos, xval, maxPos);
	$(this).css("left", left + "px");
	$(".slider-overlay").css("width", left + handleWidth/2 + "px");
}).bind("dragend", function(e){
	// constant 71px is because whole slider-handler have to be on the next slot to slide
	xPos = (71 + e.offsetX - Math.max(0, $("body").width() - sliderWidth) / 2) / posWidth;
	$(".slider-wrapper a.point").eq(Math.mid(0, xPos, posCount - 1)).click();
});

//sliding content
$(".clip").css("width", $(".clip .section").length * 852 + "px");
$(".secondary-menu a").eq(0).addClass("active");
$(".secondary-menu a").click(function(){
	var l = 0 - $(this).attr("rel") * 852;
	$(".clip").animate({marginLeft: l}, 200, "swing");
	$(".secondary-menu a").removeClass("active");
	$(this).addClass("active");
	return false;
});


//removing link outlines in IE6
if($.browser.msie && $.browser.version < 7){
	$("a").click(function(){ $(this).blur(); });
	$("a").mouseout(function(){ $(this).blur(); });
}

/**
 * Blue outline
 */
$('input[type="text"], input[type="password"], textarea').focus(function() {
	$(this).closest('span.input-text, span.textarea').addClass('field-focus');
}).blur(function() {
	$(this).closest('span.input-text, span.textarea').removeClass('field-focus');
});

