// dz
var $jq = jQuery.noConflict();
var requestData = new Object();

function goTo(url) {
    window.location = url;
}

function log(p) {
    if(typeof(console) == 'object' && typeof(console.log) == 'function') {
		console.log(p);
    }
}

function uid(){
    var r, i, j;
    r = '';
    for (j = 0; j < 32; j++) {
        i = Math.floor(Math.random() * 16).toString(16).toLowerCase();
        r = r + i;
    }
    return r
}

function strstr (haystack, needle, bool) {
    var pos = 0;
    haystack += '';
    pos = haystack.indexOf(needle);
    if (pos == -1) {
        return false;
    } else{
        if (bool){
	    return haystack.substr(0, pos);
	} else{
            return haystack.slice(pos);
        }
    }
}

var Forms = {
    list: {
		"wlr" : "/wlr",
		"standard": "/formularz_uslugi",
		"default": "/blad_formularza"
    },
    getUrl: function(name) {
		return Forms.list[name];
    }
}

var Themes = {
    colors: {
		"tv": "blue",
		"internet": "orange",
		"phone": "green",
		"standard": "blue",
		"wlr":	"blue",
		"default": "blue"
    },
    getTheme: function(context) {
		return Themes.colors[context];
    }
}

function getWindowSizes() {
	var wh = undefined;
	var ww = undefined;

	if(window.innerHeight !== undefined) {
		wh = window.innerHeight;
	} else {
		wh = document.body.clientHeight;
	}

	if(window.innerWidth !== undefined) {
		ww = window.innerWidth;
	} else {
		ww = document.body.clientWidth;
	}

	return {width: ww, height: wh};
}

function getScrollTopOffset()
{

	if(window.scrollY !== undefined) {
		return window.scrollY;
	} else {
		var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body
		var dsoctop = document.all ? iebody.scrollTop : pageYOffset
		return dsoctop/2;
	}
}


function showMessageBox(caller, title, message, mb_type, mb_yes, mb_no, mb_before) {

	// TODO: zamienić na dymicznie tworzony boks -  w wolnej chwili :>
	// <div class="messageBox"><h3></h3><p></p><div class="triggers"><a href="#" title="" class="mb_yes">Tak</a><a href="#" title="" class="mb_no">Nie</a><a href="#" title="" class="mb_ok">Ok</a></div></div>

	var mb 	= $jq(".messageBox");

	mbexpose = mb.expose({
	    maskId: "overlay_mask",
		opacity: 0.15,
		closeOnClick: false,
		closeOnEsc: false,
		api: true
	});

	if(title == "" || title == null) {
		mb.find("h3").hide();
	} else {
		mb.find("h3").html(title);
	}

	mb.find("p").html(message);
	mb.find(".mb_yes").hide();
	mb.find(".mb_no").hide();
	mb.find(".mb_ok").hide();

	switch(mb_type) {
		case 'MB_YESNO': {
			mb.find(".mb_yes").show().html("").bind("click", function() {
				mb.fadeOut("fast", function(){
					if(typeof(mb_yes) == 'function') {
						mb_yes(this);
					}
					$jq(this).unbind("click");
					mbexpose.close();
				});
				return false;
			});

			mb.find(".mb_no").show().html("").bind("click", function() {
				mb.fadeOut("fast", function(){
					if(typeof(mb_no) == 'function') {
						mb_no(this);
					}
					$jq(this).unbind("click");
					mbexpose.close();
				});
				return false;
			});
			break;
		}

		case 'MB_OK':
		default: {
			mb.find(".mb_ok").show().css('display', 'block').html("").bind("click", function() {
				mb.fadeOut("fast", function(){
					if(typeof(mb_yes) == 'function') {
						mb_yes(this);
					}
					$jq(this).unbind("click");
					mbexpose.close();
				});
				return false;
			});
			break;
		}
	}

	var top		= 0;
	var left	= 0;
	var offset	= mb.width();

	if(caller == null) {
		var ws	= getWindowSizes();
		top		= (ws.height - mb.height())/2;
		left	= (ws.width - mb.width())/2;
		top 	+= getScrollTopOffset();
	} else {
		top = $jq(caller).offset().top;
		left = $jq(caller).offset().left-offset;
	}

	$jq(window).resize(function(){
		mb.css({ "top" : top , "left" : left});
	});

	mb.css({ "top" : top , "left" : left});

	if(typeof(mb_before) == 'function') {
		mb_before(this);
	}

	mb.fadeIn("fast");
	mbexpose.load();
}

function ajaxSearch(caller, settings)
{
	settings = jQuery.extend({
		typeSearch: "any",
		promolink: Forms.getUrl("default"),
		query: "",
		city: "",
		street: "",
		house: "",
		action: "s",
		cache: false,
		forceQuit: false,
		onBefore: function() {},
		onClose: function() {}
    }, settings);

	if(typeof(pageTracker) == 'object' && typeof(pageTracker._trackEvent) == 'function') {
		pageTracker._trackEvent('locations', 'search', settings.city.toUpperCase());
	}

	$jq.ajax({
		url: "/tools/formService/parse.php",
		data: "act="+encodeURIComponent(settings.action)+"&"+"c="+encodeURIComponent(settings.city.toUpperCase())+"&s="+encodeURIComponent(settings.street.toUpperCase())+"&h="+encodeURIComponent(settings.house.toUpperCase())+"&q="+encodeURIComponent(settings.query)+"&p="+encodeURIComponent(settings.promolink),
		type: "GET",
		cache: settings.cache,
		async: false,
		dataType: "json",
		success: function(data) {
			var parsedData;
			try {
				var parsedData = eval(data);
				switch(settings.typeSearch) {
					case "any": {
						if(parsedData.any == 1) {
							goTo(settings.promolink);
						} else {
							if(settings.forceQuit) {
								// alert('sorry rambo! brak dostępnych usług');
								showMessageBox(caller, "", "Przepraszamy, usługa nie jest dostępna pod wskazanym adresem.", 'MB_OK', function(){
									settings.onClose();
								}, null, settings.onBefore);

							} else {
								showMessageBox(caller, "Brak dostępnych usług", "Zapoznaj się z ofertą telefoniczną dla Klientów TP S.A.", 'MB_YESNO',
									function(){
										goTo(Forms.getUrl("wlr"));
									}, function(){
										settings.onClose();
									}
								);
							}
						}
						break;
					}
					case "query": {
						if(parsedData.query == 1) {
							goTo(settings.promolink);
						} else {
							if(settings.forceQuit) {
								//alert('sorry rambo! brak dostępnych usług');
								showMessageBox(caller, "", "Przepraszamy, usługa nie jest dostępna pod wskazanym adresem.", 'MB_OK', function(){
									settings.onClose();
								}, null, settings.onBefore);
							} else {
								showMessageBox(caller, "Brak dostępnych usług", "Zapoznaj się z ofertą telefoniczną dla Klientów TP S.A.", 'MB_YESNO',
									function(){
										goTo(Forms.getUrl("wlr"));
									}, function(){
										settings.onClose();
									}
								);
							}
						}
						break;
					}
				}
			} catch (e) {
				showMessageBox(caller, "Brak dostępnych usług", "Zapoznaj się z ofertą telefoniczną dla Klientów TP S.A.", 'MB_YESNO',
					function(){
						goTo(Forms.getUrl("wlr"));
					}, function(){
						settings.onClose();
					}
				);
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			//alert("[ajaxSearch Error2] : "+ textStatus);
			showMessageBox(caller, "Brak dostępnych usług", "Zapoznaj się z ofertą telefoniczną dla Klientów TP S.A.", 'MB_YESNO',
				function(){
					goTo(Forms.getUrl("wlr"));
				}, function(){
					settings.onClose();
				}
			);
			expose.close();
			return false;
		}
	});
}

function clearForm()
{
	$jq("#c").defaultText(true);
    $jq("#s").defaultText(true);
    $jq("#h").defaultText(true);

	$jq("#c").val("");
	$jq("#s").val("");
	$jq("#h").val("");
}

function setDefaults()
{
	$jq("#c").attr("title", "miejscowość");
	$jq("#s").attr("title", "ulica");
	$jq("#h").attr("title", "numer domu");

	$jq("#c").defaultText();
    $jq("#s").defaultText();
    $jq("#h").defaultText();
}

function showModal(caller, typeSearch, forceQuit, promolink, query,  windowTheme)
{
	if(promolink == "") {
		prmolink == Forms.getUrl("default");
	}

	if(windowTheme == "") {
		windowTheme = Themes.getTheme("default");
	}

	var _window	= $jq("#modal_form");
    var mb 	= $jq(".messageBox");
	var theme = windowTheme;
    var uslugi	= "";

	if(typeSearch == "") {
		typeSearch = "any";
	}

    if(typeof _window != 'object' || typeof mb != 'object')
		return;

	clearForm();
	setDefaults();

    var expose = _window.expose({
        maskId: "overlay_mask",
		opacity: 0.5,
		closeOnClick: false,
		closeOnEsc: false,
		api: true
    });

    $jq("#c").autocomplete("/tools/formService/parse.php", {
		delay: 100,
		width: 181,
		minChars: 1,
		theme: "ac_"+theme,
		extraParams: {
			"c": ""
		},
		max: 10
    });

    $jq("#s").autocomplete("/tools/formService/parse.php", {
		delay: 100,
		width: 181,
		minChars: 3,
		theme: "ac_"+theme,
		extraParams: {
			"c" : function() { return $jq("#c").val().toUpperCase(); },
			"s" : ""
		},
		max: 10
    });

    expose.onClose(function() {
		$jq("#c").unautocomplete();
		$jq("#s").unautocomplete();
		_window.fadeOut("fast");
		mb.fadeOut("fast");
		_window.find(".close").unbind("click");
		_window.find(".input_nr3").unbind("click");
		_window.removeClass(theme);
    });

	var top		= 0;
	var left	= 0;
	var offset	= $jq("#modal_form").width();

	if(caller == null) {
		var ws	= getWindowSizes();
		top		= (ws.height - _window.height())/2;
		left	= (ws.width - _window.width())/2;
		top 	+= getScrollTopOffset();
	} else {
		top = $jq(caller).offset().top;
		left = $jq(caller).offset().left-offset;
	}

	_window.css({
		"z-index": "99999",
		"position": "absolute",
		"top": top+"px",
		"left": left+"px"
    });

    _window.addClass(theme);
	_window.find(".close").bind("click", function(){
		expose.close();
	});

    _window.find(".input_nr3").bind("click", function() {

		if($jq("#c").val() == "" ||
		   $jq("#c").val() == $jq("#c").attr("title") ||
		   $jq("#s").val() == "" ||
		   $jq("#s").val() == $jq("#s").attr("title") ||
		   $jq("#h").val() == "" ||
		   $jq("#h").val() == $jq("#h").attr("title") ) {
			return false;
		}

		function urlencode (str) {
			str = (str+'').toString();
			return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
		}

		var street = $jq("#s").val();
		var city = $jq("#c").val();
		var house = $jq("#h").val();

		ajaxSearch(caller, {
			typeSearch: typeSearch,
			promolink: promolink,
			query: query,
			city: city,
			street: street,
			house: house,
			forceQuit: forceQuit,
			onBefore: function() { _window.fadeOut("fast"); },
			onClose: function(){
				expose.close();
			}
		});

		return false;

	});

    _window.find(".close").bind("click", function(){
		expose.close();
    });

    _window.fadeIn("fast");

	if(typeof(pageTracker) == 'object' && typeof(pageTracker._trackEvent) == 'function') {
		pageTracker._trackEvent('locations', 'show',  promolink);
	}

	expose.load();
}

function initTabSearchForm()
{
	$jq("#tabSearchForm .tab-triggers ul").tabs($jq("#tabSearchForm .tab-content div.tabs > div"), {
		current: "current",
		effect: "default"
	});

	$jq("#c").val("");
	$jq("#s").val("");
	$jq("#h").val("");

	$jq("#c").autocomplete("/tools/formService/parse.php", {
		delay: 100,
		width: 181,
		minChars: 1,
		theme: "ac_blue",
		extraParams: {
			"c": ""
		},
		max: 10
    });

    $jq("#s").autocomplete("/tools/formService/parse.php", {
		delay: 100,
		width: 181,
		minChars: 3,
		theme: "ac_blue",
		extraParams: {
			"c" : function() { return $jq("#c").val().toUpperCase(); },
			"s" : ""
		},
		max: 10
    });

	$jq("#checkServices").bind("click", function(){
		if($jq("#c").val() == "" ||
		   $jq("#c").val() == $jq("#c").attr("title") ||
		   $jq("#s").val() == "" ||
		   $jq("#s").val() == $jq("#s").attr("title") ||
		   $jq("#h").val() == "" ||
		   $jq("#h").val() == $jq("#h").attr("title") ) {
				showMessageBox(null, "", "Prosze wypełnić wszystkie pola formularza", "MB_OK", null, null);
			return false;
		} else {
			ajaxSearch(null, {
				typeSearch: "any",
				city: $jq("#c").val(),
				street: $jq("#s").val(),
				house: $jq("#h").val(),
				forceQuit: false,
				promolink: Forms.getUrl("standard"),
				onClose: function(){
					clearForm();
				}
			});
			return false;
		}
	});
}

function inArray(a, v){
	for(var i in a) {
		if(a[i] == v) {
			return true;
		}
	}
	return false;
}


/* w końcu trzeba by cos zrobić z tym zlepkiem funkcji */
var mmInfo = {
	exclude: {
		'adult':		['rozrywka', 'canalplus'],
		'komfort':		[],
		'basic':		[],
		'basicplus':	['canalplus', 'adult', 'rozrywka'],
		'canalplus':	['rozrywka', 'adult'],
		'rozrywka':		['adult', 'canalplus'],
		'mamjuz':		[],
		'dom':			[],
		'komfortplus':	[],
		'iptv-komfort':	[],
		'komfortpvr':	[],
		'axn':			['film'],
		'film':			['axn']
    },

	include: {
		'canalplushd':	['canalplus'],
		'hbohd':		['hbo'],
		'hbo':			['hbohd']
	},

	promotions: {
		'komfort':		['canalplus', 'film', 'kids', 'sport', 'hbo', 'hbohd', 'canalplushd'],
		'komfortpvr':	['canalplus', 'film', 'kids', 'sport', 'hbo', 'hbohd', 'canalplushd'],
		'basicplus':	[],
		'basic':		['canalplus', 'film', 'kids', 'sport', 'hbo', 'hbohd', 'canalplushd'],
		'dom':			['dom', 'iptv-komfort', 'komfortplus', 'canalplus', 'hbo', 'hbohd', 'canalplushd'],
		'iptv-komfort':	['dom', 'iptv-komfort', 'komfortplus', 'canalplus', 'hbo', 'hbohd', 'canalplushd'],
		'komfortplus':	['dom', 'iptv-komfort', 'komfortplus', 'canalplus', 'hbo', 'hbohd', 'canalplushd'],
		'mamjuz':		['dom', 'iptv-komfort', 'komfortplus', 'canalplus', 'hbo', 'hbohd']//,
	},

	triggers: {
		'basic': ['film', 'kids', 'sport'],
		'komfort': ['film', 'kids', 'sport'],
		'komfortpvr': ['film', 'kids', 'sport'],

		each: function(callback) {
			if(typeof(callback) == 'function') {
				for(i in mmInfo.triggers) {
					if($jq('#'+i).is(':checked')) {
						for(j in mmInfo.triggers[i]) {
							callback(mmInfo.triggers[i][j]);
						}
					}
				}
			}
		},

		canUncheck: function(triggerId) {
			var result = true;
			mmInfo.triggers.each(function(id) {
				if(triggerId == id) {
					result = false;
				}
			});
			return result;
		}

	},

	count: {
		'komfort': 84,
		'komfortpvr': 84,
		'basic': 40,
		'basicplus': 51,
		'rozrywka': 9,
		'canalplus': 4,
		'adult': 5,
		'film': 9,
		'filmboxekstra': 3,
		'axn': 2,
		'kids': 7,
		'cinemax': 2,
		'hbo': 6,
		'hbohd': 1,
		'sport': 6,
		'canalplushd': 2,
		'hd': 5,
		'sportbasic': 4,

		'dom': 41,
		'komfortplus': 78,
		'filmbox': 3,

		'iptv-kids': 6,
		'iptv-komfort': 59
	},

	$$: {
		'dtv': 0,
		'iptv': 0
	},

	activationPrice: {
		'basic': 29,
		'komfort': 29,
		'komfortpvr': 99,
		'komfortplus': 54,
		'iptv-komfort': 49,
		'dom': 49,
		'defaultValue': 0
	},

	checkDependency: function(chanelId) {
		if((chanelId == 'hbo' && $jq('#hbohd').is(':checked')) && ($jq('#komfort').is(':checked') || $jq('#komfortpvr').is(':checked') || $jq('#dom').is(':checked') || $jq('#iptv-komfort').is(':checked') || $jq('#komfortplus').is(':checked') )) {
				return false;
		}
		if((chanelId == 'canalplus' && $jq('#canalplushd').is(':checked')) && ($jq('#komfort').is(':checked') || $jq('#komfortpvr').is(':checked') || $jq('#dom').is(':checked') || $jq('#iptv-komfort').is(':checked') || $jq('#komfortplus').is(':checked') )) {
				return false;
		}


		return true;
	},

	resolveDependency: function(chanelId, event) {

		if($jq('#'+chanelId).is(':radio')) {
			$jq('.sidebar dd.promotion').removeClass('promotion');

			for(i in mmInfo.promotions) {
				if(i == chanelId) {
					for(j in mmInfo.promotions[i]) {
						$jq('#'+mmInfo.promotions[i][j]).parent().addClass('promotion');
					}
				}
			}

			mmInfo.triggers.each(function(id) {
				$jq('#'+id).attr('disabled', true);
			});

		}

		if($jq('#komfort').is(':checked') || $jq('#komfortpvr').is(':checked') || $jq('#basic').is(':checked') || $jq('#dom').is(':checked') || $jq('#iptv-komfort').is(':checked') || $jq('#komfortplus').is(':checked')) {
			switch(chanelId) {
				/*case 'hbo': {
					if($jq('#hbo').is(':checked') && !$jq('#hbohd1').is(':checked')) {
						$jq('#hbohd').trigger('click');
						$jq('#hbohd').attr('checked', true);
						$jq('#channels').find('span.'+chanelId+'-ex').parent().addClass('hbohd-selected');
						cbHelper.increment($jq('#hbohd'), event);
					}
					break;
				}*/
				case 'hbohd': {
					if($jq('#hbohd').is(':checked') && !$jq('#hbo').is(':checked')) {
						$jq('#hbo', event.currentTarget). trigger('click');
						log(event);
						// $jq('#hbo').attr('checked', true);
						$jq('#channels').find('span.'+chanelId+'-ex').parent().addClass('hbo-selected');
						cbHelper.increment($jq('#hbo'), event);
						// cbHelper.increment($jq('#hbohd'), event);
					}
					break;
				}

				case 'canalplushd': {
					if(($jq('#canalplushd').is(':checked') && !$jq('#canalplus').is(':checked')) && !$jq('#basicplus').is(':checked')) {
						$jq('#canalplus').trigger('click');
						$jq('#canalplus').attr('checked', true);
						$jq('#channels').find('span.'+chanelId+'-ex').parent().addClass('canalplus-selected');
						cbHelper.increment($jq('#canalplus'), event);
					}
					break;
				}
			}
		}

	}
};

//------------------------------------------------------------------------------

var cbHelper = {
	increment: function(obj, event) {
			var channels = parseInt($jq('#channels-count').find('.value').html());
			var pkg		= parseInt($jq('#pkg-count').find('.value').html());
			var price	= parseFloat($jq(obj).parent().find('.value').html());

			var newPrice = 0;
			var newPromo = 0;

			var li = $jq('#pakiety li.'+obj.id);

			$jq('#channels').find('span.'+obj.id).parent().addClass(obj.id+'-selected');
			$jq(obj).parent().addClass('check-selected');

			pkg++;

			newPrice = parseFloat($jq('#price .value').html()) + price;

			if($jq(obj).parent().hasClass('promotion')) {
				newPromo = parseFloat($jq('#promo-count .value').html()) + parseFloat($jq(obj).parent().find('.new-value').html());
			} else {
				newPromo = parseFloat($jq('#promo-count .value').html()) + price;
			}

			if(li.length == 0) {
				li = $jq('<li>').addClass(obj.id).appendTo('#pakiety');
			}

			if(mmInfo.count[obj.id] != undefined) {
				channels +=  parseInt(mmInfo.count[obj.id]);
			}

			li.html($jq(obj).parent().find('.name').html());

			$jq('#channels-count .value').html(channels);
			$jq('#pkg-count .value').html(pkg);
			$jq('#price .value').html(newPrice.toFixed(2));
			$jq('#cena_podstawowa .value').html(newPrice.toFixed(2));
			$jq('#cena_promocyjna .value').html(newPromo.toFixed(2));
			$jq('#promo-count .value').html(newPromo.toFixed(2));

	},

	decrement: function(obj, event) {

			var channels = parseInt($jq('#channels-count').find('.value').html());
			var pkg		= parseInt($jq('#pkg-count').find('.value').html());
			var price	= parseFloat($jq(obj).parent().find('.value').html());

			var newPrice = 0;
			var newPromo = 0;

			var li = $jq('#pakiety li.'+obj.id);

			$jq('#channels').find('span.'+obj.id).parent().removeClass(obj.id+'-selected');

			$jq(obj).parent().removeClass('check-selected');
			pkg--;
			newPrice = parseFloat($jq('#price .value').html()) - price;

			if($jq(obj).parent().hasClass('promotion')) {
				newPromo = parseFloat($jq('#promo-count .value').html()) - parseFloat($jq(obj).parent().find('.new-value').html());
			} else {
				newPromo = parseFloat($jq('#promo-count .value').html()) - price;
			}

			if(li.length > 0) {
				li.remove();
			}

			if(mmInfo.count[obj.id] != undefined) {
				channels -=  parseInt(mmInfo.count[obj.id]);
			}

			$jq('#channels-count .value').html(channels);
			$jq('#pkg-count .value').html(pkg);
			$jq('#price .value').html(newPrice.toFixed(2));
			$jq('#cena_podstawowa .value').html(newPrice.toFixed(2));
			$jq('#cena_promocyjna .value').html(newPromo.toFixed(2));
			$jq('#promo-count .value').html(newPromo.toFixed(2));
	},

	runTriggers: function(id) {
		function c(id) { setTimeout(function(){$jq(id).triggerHandler('click');}, 100); }
		for(i in mmInfo.triggers) {
			if(i == id) {
				for(j in mmInfo.triggers[i]) {
					$jq('#'+mmInfo.triggers[i][j]).attr('checked', true).triggerHandler('click');
					c('#'+mmInfo.triggers[i][j]);
				}
			}
		}
	}
}

function setupPackageChoser() {

	function buildLinkOptions(alias) {
		var context = $jq('#tabsheet-order-form form:first-child').hasClass('dtv') ? 'op_tv=1' : 'op_tv=2';
		var pakiet 	= 'pakiet=' + String($jq('#tabsheet-order-form form:first-child input[type=radio]:checked').val());
		var options = '';

		$jq('#tabsheet-order-form .tab-content .pane-1 .sidebar dl dd input[type=checkbox]').each(function(index, Element) {
			if($jq(this).is(':checked')) {
				options += '&op'+String(this.value)+String('=1');
			}
		});

		alias += String('?')+context.toString() + String('&')+pakiet.toString();

		if(options != '') {
			alias += options.toString();
		}

		return alias;
	}

	function onRadioClick(event) {

		if($jq(this).parent().hasClass('highlight')) {
			return;
		}

		$jq('#pakiety').html('');
		$jq('#channels').find('.chanel-selected').removeClass('chanel-selected');

		$jq('#tabsheet-order-form .tab-content .pane-1 .sidebar input[type=checkbox]:checked').each(function(i, o){
			$jq('#channels '+'.'+o.id+'-selected').removeClass(o.id+'-selected');
		});

		$jq('#channels').find('span.'+this.id).parent().addClass('chanel-selected');
		$jq(this).parent().parent().find('.selected').removeClass('selected');
		$jq(this).parent().addClass('selected');
		$jq(this).parent().parent().find('.highlight').removeClass('highlight');
		$jq(this).parent().addClass('highlight');

		var channels = parseInt($jq('#channels-count').find('.value').html());
		var pkg		= 0;
		var price	= parseFloat($jq(this).parent().find('.value').html());
		var promo 	= parseFloat(price);

		$jq('#tabsheet-order-form .tab-content .pane-1 .sidebar dl dd input[type=checkbox]').each(function(index, Element) {
			if($jq(this).is(':checked')) {
				$jq(this).attr('checked', false);
				$jq(this).parent().removeClass('check-selected');
				channels -= parseInt($jq(this).parent().find('.value').html());
				$jq('#mamjuz').parent().find('.value').html(channels);
			}
			if($jq(this).is(':disabled')) {
				$jq(this).attr('disabled', false);
			}
		});

		if($jq(this).is(':checked') && this.id != 'mamjuz') {
			if(mmInfo.count[this.id] != undefined) {

				channels -= parseInt($jq('#mamjuz').parent().find('.value').html());
				channels += mmInfo.count[this.id];
				pkg++;
				$jq('#mamjuz').parent().find('.value').html(mmInfo.count[this.id]);
				var li = $jq('#pakiety li.standard-pkg');

				if(li.length == 0) {
					li = $jq('<li>').addClass('standard-pkg').addClass(this.id).appendTo('#pakiety');
				}
				li.html($jq(this).parent().find('.name').html());
				for(i = 0; i < mmInfo.exclude[this.id].length; i++) {
					$jq('#'+mmInfo.exclude[this.id][i]).attr('disabled', true);
				}

				if($jq(this).parent().hasClass('promotion')) {
					promo = parseFloat($jq(this).parent().find('.new-value').html());
				}

				if($jq('form.dtv').length > 0) {
					price += parseFloat(mmInfo.$$['dtv']);
					promo += parseFloat(mmInfo.$$['dtv']);
				}
				if($jq('form.iptv').length > 0) {
					price += parseFloat(mmInfo.$$['iptv']);
					promo += parseFloat(mmInfo.$$['iptv']);
				}
			}
		} else if(this.id == 'mamjuz') {
			channels = 0;
			price	= 0;
			promo = 0;
			$jq('#mamjuz').parent().find('.value').html('0');
			$jq('#pakiety li.standard-pkg').remove();
		}

		mmInfo.resolveDependency(this.id);
		cbHelper.runTriggers(this.id);

		$jq('#channels-count .value').html(channels);
		$jq('#pkg-count .value').html(pkg);
		$jq('#price .value').html(price.toFixed(2));
		$jq('#cena_podstawowa .value').html(price.toFixed(2));
		$jq('#cena_promocyjna .value').html(promo.toFixed(2));
		$jq('#promo-count .value').html(promo.toFixed(2));
	}

	function onCheckClick(event) {

		mmInfo.resolveDependency(this.id, event);

		if($jq(this).is(':checked')) {
			switch(this.id) {
				case 'axn': {
					$jq('#film').attr('disabled', $jq('#axn').attr('checked'));
					break;
				}

				case 'film': {
					$jq('#axn').attr('disabled', $jq('#film').attr('checked'));
					break;
				}

				case 'rozrywka': {
					$jq('#canalplus').attr('disabled', $jq('#rozrywka').attr('checked'));
					$jq('#adult').attr('disabled', $jq('#rozrywka').attr('checked'));
					break;
				}

				case 'canalplus': {
					if(!$jq('#rozrywka').attr('disabled') && $jq('#canalplus').attr('checked') || $jq('#adult').attr('checked')) {
						$jq('#rozrywka').attr('disabled', true);
					}
					break;
				}

				case 'adult': {
					if(!$jq('#rozrywka').attr('disabled') && $jq('#canalplus').attr('checked') || $jq('#adult').attr('checked')) {
						$jq('#rozrywka').attr('disabled', true);
					}
					break;
				}
			}
			cbHelper.increment(this, event);

		} else {

			if(!mmInfo.triggers.canUncheck(this.id)) {
				return false;
			}

			switch(this.id) {
				case 'hbo':
				// case 'hbohd':
				case 'canalplus': {
					if(!mmInfo.checkDependency(this.id)) {
						return false;
					}
					if($jq('#rozrywka').attr('disabled') && !$jq('#adult').attr('checked')) {
						$jq('#rozrywka').attr('disabled', false);
					}
					break;
				}

				case 'axn': {
					$jq('#film').attr('disabled', $jq('#axn').attr('checked'));
					break;
				}

				case 'film': {
					$jq('#axn').attr('disabled', $jq('#film').attr('checked'));
					break;
				}

				case 'rozrywka': {
					$jq('#canalplus').attr('disabled', $jq('#rozrywka').attr('checked'));
					$jq('#adult').attr('disabled', $jq('#rozrywka').attr('checked'));
					break;
				}

				case 'adult': {
					if($jq('#rozrywka').attr('disabled') && !$jq('#canalplus').attr('checked')) {
						$jq('#rozrywka').attr('disabled', false);
					}
					break;
				}
			}
			cbHelper.decrement(this, event);
		}

		return true;
	}

	$jq('#tabsheet-order-form .tab-content .pane-1 .sidebar dl dd input[type=radio]').bind('click', onRadioClick);
	$jq('#tabsheet-order-form .tab-content .pane-1 .sidebar dl dd input[type=checkbox]').click(onCheckClick);


	$jq('#go_order').bind('click', function() {
		if($jq('#tabsheet-order-form form:first-child').hasClass('dtv')) {
			showModal(null, 'query', true, buildLinkOptions('/formularz_promocja_tv_dtv'), 'dtv', 'blue');
		} else {
			showModal(null, 'query', true, buildLinkOptions('/formularz_promocja_tv_iptv'), 'dtv', 'blue');
		}
		return false;
	});

	if($jq('#tabsheet-order-form').length > 0) {
		$jq('body').css('overflow-y', 'scroll');
	}

	// zmiana #go_next na .go_next, 27 07 2010 Arek
	$jq('.go_next').bind('click', function(){
		if($jq(this).parent().hasClass('tab-active')) return false;
		$jq('#tabsheet-order-form').find('.tab-active').removeClass('tab-active').next().addClass('tab-active');
		$jq('#tabsheet-order-form .tab-content .panes .pane-1').hide();
		$jq('#tabsheet-order-form .tab-content .panes .pane-2').show();


		/*if($jq('.sidebar').find('input[type=checkbox]:checked').length > 0) {
			 $jq('#oplata_aktywacyjna').find('.value').text(0);
		} else */
		if($jq('#komfort').is(':checked')) {
			$jq('#oplata_aktywacyjna').find('.value').text(mmInfo.activationPrice.komfort);
		} else if($jq('#komfortpvr').is(':checked')) {
			$jq('#oplata_aktywacyjna').find('.value').text(mmInfo.activationPrice.komfortpvr);
		} else if($jq('#dom').is(':checked')) {
			$jq('#oplata_aktywacyjna').find('.value').text(mmInfo.activationPrice.dom);
		} else if($jq('#iptv-komfort').is(':checked')) {
			$jq('#oplata_aktywacyjna').find('.value').text(mmInfo.activationPrice.iptv-komfort);
		} else if($jq('#komfortplus').is(':checked')) {
			$jq('#oplata_aktywacyjna').find('.value').text(mmInfo.activationPrice.komfortplus);
		} else if($jq('#basic').is(':checked')) {
			$jq('#oplata_aktywacyjna').find('.value').text(mmInfo.activationPrice.basic);
		} else {
			$jq('#oplata_aktywacyjna').find('.value').text(mmInfo.activationPrice.defaultValue);
		}

		return false;
	});

	// zmiana #go_back na .go_back, 27 07 2010 Arek
	$jq('.go_back').bind('click', function(){
		if($jq(this).parent().hasClass('tab-active')) return false;
		$jq('#tabsheet-order-form').find('.tab-active').removeClass('tab-active').prev().addClass('tab-active');
		$jq('#tabsheet-order-form .tab-content .panes .pane-2').hide();
		$jq('#tabsheet-order-form .tab-content .panes .pane-1').show();
		return false;
	});
}

$jq(document).ready(function($) {

	if($("#tabSearchForm").length > 0) {
		initTabSearchForm();
	}

	if($jq('#tabsheet-order-form').length > 0) {
		setupPackageChoser();
	}

	$('#sledzik').click(function(){
		if(typeof(pageTracker) == 'object' && typeof(pageTracker._trackEvent) == 'function') {
			pageTracker._trackEvent('locations', 'show', 'main-page');
		}
	});

	if($('form.dtv').length > 0) {
		$('form.dtv')[0].reset();
	}

	if($('form.iptv').length > 0) {
		$('form.iptv')[0].reset();
	}

	$('.tt2').click(function(){return false;});

	if($jq('#basic').length > 0) {
		mmInfo.resolveDependency('basic');
		$jq('#basic').attr('checked', true).trigger('click');
	}

	if($jq('#komfortplus').length > 0) {
		mmInfo.resolveDependency('komfortplus');
		$jq('#komfortplus').attr('checked', true).trigger('click');
	}

	$jq('#maps_calosc .filter').click(function(e){
		e.preventDefault();
		$jq(this).toggleClass('active');

		if( $jq(this).hasClass('opt_i900') ) {
		  showPolygons('i900')
		} else if ( $jq(this).hasClass('opt_o900') ) {
		  showPolygons('o900')
		} else if ( $jq(this).hasClass('opt_i2100') ) {
		  showPolygons('i2100')
		} else {
		  showPolygons('o2100')
		}
	});

});


(function(){
	//var jq = jQuery.noConflict();
	$jq(document).ready(function() {

		$jq('#vod-picturebox > .content > .overlay').css({opacity: 0.5});

		$jq('#vod-picturebox .blank').attr('target', "blank");

		var popinBartka = {
			current: null,
			currentHeight: 430,
			TOGGLE_PREV: 0,
			TOGGLE_NEXT: 1,

			show: function(element) {
				var self = this;
				self.current = element;
				self.loadContent(element);
				// self.checkTrailerContent(element);

				$jq('#vod-picturebox > .content > .overlay').fadeIn("fast", function() {
					var popin = $jq('#popinBartka').height(self.currentHeight);
					popin.css({top: "-"+self.currentHeight+"px"}).show().stop().animate({top: "156px"}, 600, function() {

						popin.find('.btn-close').click(function() {
							self.close();
							return false;
						});

						popin.find('.btn-prev').click(function() {
							self.toggleContent(self.TOGGLE_PREV);
							return false;
						});

						popin.find('.btn-next').click(function() {
							self.toggleContent(self.TOGGLE_NEXT);
							return false;
						});
					});
				}).click(function() {
					self.close();
					return false;
				});
			},

			/*checkTrailerContent: function(element) {
				var contents = $jq(element).parent().parent().find('.lightboxInfo').find('.trailer');
				if(contents.length > 0) {
					this.currentHeight = 560;
				} else {
					this.currentHeight = 360;
				}
			},*/

			toggleContent: function(direction) {
				var toShow = null;
				var currentParent = $jq(popinBartka.current).parent().parent();

				if(direction == this.TOGGLE_PREV) {
					toShow = currentParent.prev('li').find('.details a');
					if(toShow.length < 1) {
						toShow = currentParent.parent().find('li:last-child').find('.details a');
					}
				} else if(direction == this.TOGGLE_NEXT) {
					toShow = currentParent.next('li').find('.details a');
					if(toShow.length < 1) {
						toShow = currentParent.parent().find('li:first-child').find('.details a');
					}
				}

				popinBartka.loadContent(toShow);
				popinBartka.current = toShow;
			},

			loadContent: function(element) {
				var self = this;
				var contents = $jq(element).parent().parent().find('.lightboxInfo');
				var content = contents.find('.content').clone(true);
				var picture = contents.find('.picture').clone(true);
				var trailer = contents.find('.trailer').clone(true);

				var popin = $jq('#popinBartka');
				popin.find('.content').replaceWith(content);
				popin.find('.picture').replaceWith(picture);


				if(trailer.length > 0) {
					self.currentHeight = 630;
					popin.find('.trailer').replaceWith(trailer.show()).show();
					popin.height(630);
					var ph = popin.find('.trailer-placeholder');

					var flashvars = {
						flvPath: ph.attr('href')
					};
					var params = {  wmode: "transparent" };
					var attributes = { };
					swfobject.embedSWF("/swf/flv_player/320x180/flvplayer.swf", ph.attr('id'), "320", "180", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
				} else {
					this.currentHeight = 430;
					popin.height(430).find('.trailer').hide().empty();
				}
			},

			close: function() {
				var popin = $jq('#popinBartka');
				popin.stop().animate({top: "-"+this.currentHeight+"px"}, 600, function() {
					$jq('#vod-picturebox .content .overlay').fadeOut("fast", function(){
						popin.hide().find('.btn-close').unbind('click');
						popin.find('.btn-next').unbind('click');
						popin.find('.btn-prev').unbind('click');
					});
				});
			}
		};

		$jq('#vod-picturebox a.trailer-placeholder').click(function(){return false;});
		$jq('#vod-picturebox .content > ul li a').click(function() {
			popinBartka.show(this);
			return false;
		});

		if( $jq('#maps_calosc .filter').length > 0 ) {
		  $jq('#maps_calosc .filter').toggleClass('active');

		  showPolygons('i900');
		  showPolygons('o900');
		  showPolygons('i2100');
		  showPolygons('o2100');

		}

	});
})();

