$(function () {

	// podliczenie koncowej wartosci zamowienia
	$('#order-payment input[type=radio]').click(function () {
		// przeliczenie cen jesli korzystamy z platnosci
		var payment = $(this).val();
		$.each($(".price-value"), function() {
			var value = parseFloat($(this).attr("price"));
			if(payment == 1) value = Math.round(value*100/0.98)/100;
			$(this).html(value);
		});
		
		// aktualizacja ceny koncowej
		var parent = $(this).parent()
		var subtotal = $('#price-subtotal').eq(0).text();
		var cost = $(parent).find('span.cost').eq(0).text();
        total_cost = parseFloat(cost)+parseFloat(subtotal);
        total_cost = Math.round(total_cost*100)/100.0;
		$('#price-total').text(total_cost).effect('highlight', {}, 600);		
	});

	// banery flash
	if ($('#banner-home').get(0))
	{
		flashembed('banner-home', { src: $("base").attr("href") + '/static/media/baner_home.swf', wmode: 'transparent', 'width': 540, 'height': 190 })
	}

	if ($('#banner-left').get(0))
	{
		flashembed('banner-left', { src: $("base").attr("href") + '/static/media/baner_lewa.swf', wmode: 'transparent', 'width': 200, 'height': 200 })
	}

    if ($('#banner-hotmind').get(0))
	{
		flashembed('banner-hotmind', { src: $("base").attr("href") + '/static/flash/hotmind.swf', wmode: 'transparent', 'width': 200, 'height': 160 })
	}
    
    // swapy dla inputow z cenami i sliderem
    function swap_price(slider, input_from, input_to, input_max) {
    	var price_from = parseInt($("#"+input_from).val());
		var price_to = parseInt($("#"+input_to).val());
		var price_max = parseInt($("#"+input_max).val());
		if(price_from > price_to && price_from < price_max) {
			var temp = price_to;
			price_to = price_from;
			price_from = temp;
		} else if(price_from > price_max) price_from = 0;
		if(price_to > price_max) price_to = price_max;
		$("#"+input_from).val(price_from);
		$("#"+input_to).val(price_to);
		$("#"+slider).slider("values", 1, price_to);
		$("#"+slider).slider("values", 0, price_from);
    }
	$("#nb_price_from").change(function() { swap_price("nb-price-slider", "nb_price_from", "nb_price_to", "nb_max_price"); });
	$("#nb_price_to").change(function() { swap_price("nb-price-slider", "nb_price_from", "nb_price_to", "nb_max_price"); });
	$("#price_from").change(function() { swap_price("filter-slider", "price_from", "price_to", "filter_max_price"); });
	$("#price_to").change(function() { swap_price("filter-slider", "price_from", "price_to", "filter_max_price"); });
	
	// kornery dla boxow z cenami i zdjeciami, remover z porownywarki i szybki kontakt
	if(!$.browser.msie) {
		$(".border-radius-photo").corner("8px");
		$(".border-radius-price").corner("5px tl br");
		$(".border-radius-remover").corner("5px tr bl");
	} else {
		$(".border-radius-photo").css("border", "1px solid #424242");
		$(".border-radius-price").css("border", "1px solid #5C0000");
	}
	$("table.quick-contact td img.border-radius-qc").corner("9px");

    // statusy gg
    $.each($(".gg a span"), function() {
        var this_span = $(this);
        var gg = $(this).attr("id").replace(/gg/, "");
        $.ajax({
            url: $("base").attr("href") + 'gg/' + gg,
            success: function(data) {
                if(data > 1) {
                    this_span.removeClass("unavailable");
                }
            }
        });
    });
    
    // tooltipy dla dostepnosci
    $("#product-list td.availability div, #product-summary table.table-prices tr.product-availability div").qtip({
    	style: {
    		name: 'light',
    		tip: true,
    		border: {
        		color: '#c5c5c5',
        		width: 3,
        		radius: 5
        	},
        	content: {
        		color: '#123456'
        	}
    	},
    	position: {
	      corner: {
	         target: 'topRight',
	         tooltip: 'bottomRight'
	      }
	   }
    });
    
    // tooltipy dla gwarancji
    $(".warranty span, .product-warranty span").qtip({
    	style: {
    		name: 'light',
    		tip: true,
    		border: {
        		color: '#c5c5c5',
        		width: 3,
        		radius: 5
        	},
        	content: {
        		color: '#123456'
        	}
    	},
    	position: {
	      corner: {
	         target: 'bottomRight',
	         tooltip: 'topRight'
	      }
	   }
    });
	
	// nalozenie linkow do przechowalni i koszyka
	var storage = $(".storage-value");
	var storage_link = storage.find("a").attr("href");
	var cart = $(".cart-value");
	var cart_link = $(".cart-value").find("a").attr("href");
	storage.next().click(function() {
		window.location.href = storage_link;
	});
	storage.prev().click(function(){
		window.location.href = storage_link;
	});
	cart.next().click(function() {
		window.location.href = cart_link;
	});
	cart.prev().click(function() {
		window.location.href = cart_link;
	});
	
	// wyszukiwanie laptopow
	$("#notebooki-box h3").click(function() {
		$("#notebooki-box .content").slideToggle("slow");
		$.ajax({ url: $("base").attr("href")+'nb' });
	});
	$("#nb_rozdzielczosc").next().children().click(function() {
		$("#nb_rozdzielczosc").slideToggle();
		$.ajax({ url: $("base").attr("href")+'nb/resolution' });
	});
	$(".nb_cena").focus(function() {
		$("#notebooki-box input[name=cena]").removeAttr("checked");		
	});
	$("#notebooki-box input[name=cena]").change(function() {
		$(".nb_cena").val("");		
	});
	
	/* ostatnio przegladane */
	$("#last-viewed .header").click(function() {
		$("#last-viewed ul").slideToggle("slow");
		$.ajax({ url: $("base").attr("href")+'nb/last_viewed' });
	});

	// globalnie wyłącz cache dla XHR
	$.ajaxSetup({
		cache: false,
		global: true,
		complete: function () { forms_focus(); rank_stars() }
	})

	// zaznacz aktualną stronę
	var slug = $('body').attr('class')
	$('.link-' + slug).addClass('active')

	// utwórz zakładki
	$('.tabs:not(.user)').tabs({
		fx: { height: 'toggle', opacity: 'toggle' },
		spinner: 'Ładowanie&hellip;',
		ajaxOptions: { async: false }
	})

	$('.link-print').click(function () {
		window.open($(this).attr('href'), 'print', 'width=600,height=400,status=yes,menubar=yes,scrollbars=yes,resizable=yes')
		return false
	})

	// galeria zdjęć na podstronie produktu
	$('.photos a').click(function () {
		var img = new Image()
		var rel = $(this).attr('rel')
		$(img).attr('src', $(this).attr('href')).ready(function () {
			$('#photo-main img').attr('src', $(img).attr('src'))
			$('#photo-main a').attr('href', rel)
		})
		return false
	})

	/*$.Lightbox.construct({
		text: {
			image:		'Zdjęcie',
			of:			'z',
			close:		'Zamknij [x]',
			closeInfo:	'Aby zamknąć, możesz kliknąć w ciemny obszar.',
			download:	'Pobierz.',
			help: {
				close:		'Kliknij aby zamknąć',
				interact:	'Najedź'
			},
			about: {
				text: 	'PCKOM',
				title:	'',
				link:	''
			}
		}
	})*/

	$('#photo-main a').lightBox()

	// hover na tabelkach
	$('table.table-orders tr, table.table-parameters tr, table.table-reviews tr, table.table-cart tr, table.table-addresses tr')
		.live('mouseover', function () { $(this).addClass('hover') } )
		.live('mouseout', function () { $(this).removeClass('hover') } )

    $('table.table-compare tr.parameter')
        .live('mouseover', function () { $(this).addClass('hover') } )
		.live('mouseout', function () { $(this).removeClass('hover') } )
		
	// Zamów rozmowę z konsultantem
	$('a.link-consultant').live('click', function () {

		$('<div></div>')
			.attr('id', 'dialog')
			//.addClass('content')
			.dialog({
				bgiframe: true,
				autoOpen: false,
				height: 320,
				width: 450,
				modal: true,
				title: 'Rozmowa z konsultantem',
				buttons: {
					'Zamknij': function() {
						$(this).dialog('close');
					},
					'Prześlij': function () {

						var action = $(this).find('form.form-consultant').attr('action')
						var form_data = $(this).find('form.form-consultant').serialize()

						$.ajax({
							type: 'POST',
							url: action,
							data: form_data,
							container: $(this),
							success: function (result) {
								if (result == 'ok')
								{
                                    $(this.container).dialog('enable')
                                    $(this.container).empty()
                                    $(this.container).html('<div class="content">Dzi\u0119kujemy za zainteresowanie naszą ofertą. Nasz handlowiec odpowie na Twoje pytanie najszybciej jak to możliwe.</div>')
                                    $(".ui-dialog-buttonpane button:last").remove()
								}
								else
								{
									$(this.container).empty()
									$(this.container).html(result)
									$('#dialog').find('.button').remove()
								}
							},
							beforeSend: function () {
								//$('input, textarea, select, button', this.container).attr('disabled', 'disabled')
								$(this.container).dialog('disable')
							},
							complete: function () {
								//$('input, textarea, select, button', this.container).removeAttr('disabled')
								$(this.container).dialog('enable')
							}
						})

						return false

					}
				}
			})

		$('#dialog').load($(this).attr('href'), {}, function () {
			$('#dialog').find('.button').remove()
			$('#dialog').dialog('open')
		})

		$('#dialog').find('form.form-consultant').live('submit', function () { return false })

		return false

	})

	// Zgłoś błąd w opisie
	$('a.link-description-mistake').live('click', function () {

		$('<div></div>')
			.attr('id', 'dialog-description-mistake')
			//.addClass('content')
			.dialog({
				bgiframe: true,
				autoOpen: false,
				height: 200,
				width: 350,
				modal: true,
				title: 'Zgłoś błąd w opisie',
				buttons: {
					'Zamknij': function() {
						$(this).dialog('close');
					},
					'Zgłoś': function () {

						var action = $(this).find('form.form-description-mistake').attr('action')
						var form_data = $(this).find('form.form-description-mistake').serialize()

						$.ajax({
							type: 'POST',
							url: action,
							data: form_data,
							container: $(this),
							success: function (result) {
								if (result == 'ok')
								{
									$(this.container).dialog('close')
								}
								else
								{
									$(this.container).empty()
									$(this.container).html(result)
									$('#dialog-description-mistake').find('.button').remove()
								}
							},
							beforeSend: function () {
								//$('input, textarea, select, button', this.container).attr('disabled', 'disabled')
								$(this.container).dialog('disable')
							},
							complete: function () {
								//$('input, textarea, select, button', this.container).removeAttr('disabled')
								$(this.container).dialog('enable')
							}
						})

						return false

					}
				}
			})

		$('#dialog-description-mistake').load($(this).attr('href'), {}, function () {
			$('#dialog-description-mistake').find('.button').remove()
			$('#dialog-description-mistake').dialog('open')
		})

		$('#dialog-description-mistake').find('form.form-description-mistake').live('submit', function () { return false })

		return false

	})

	// Dodaj opinię
	$('div#tab-reviews a.link-add-review').live('click', function () {

		var href = $(this).attr('href')
		if (href == '#') return false

		$('<div></div>')
			.attr('id', 'dialog-add-review')
			.addClass('content')
			.dialog({
				bgiframe: true,
				autoOpen: false,
				height: 300,
				width: 450,
				modal: true,
				title: 'Dodaj opinię',
				buttons: {
					'Zamknij': function() {
						$(this).dialog('close');
					},
					'Dodaj': function () {

						var action = $(this).find('form.form-add-review').attr('action')
						var form_data = $(this).find('form.form-add-review').serialize()

						$.ajax({
							type: 'POST',
							url: action,
							data: form_data,
							container: $(this),
							success: function (result) {
								if (result == 'ok')
								{
									$(this.container).dialog('close')
								}
								else
								{
									$(this.container).empty()
									$(this.container).html(result)
									$('#dialog-add-review').find('.button').remove()
								}
								rank_stars()
							},
							beforeSend: function () {
								//$('input, textarea, select, button', this.container).attr('disabled', 'disabled')
								$(this.container).dialog('disable')
							},
							complete: function () {
								//$('input, textarea, select, button', this.container).removeAttr('disabled')
								$(this.container).dialog('enable')
							}
						})

						return false

					}
				}
			})

		$('#dialog-add-review').load($(this).attr('href'), {}, function () {
			$('#dialog-add-review').find('.button').remove()
			$('#dialog-add-review').dialog('open')
			rank_stars()
		})

		$('#dialog-add-review').find('form.form-add-review').live('submit', function () { return false })

		return false

	})

	// Dodaj opinię
	$('ul.rank li a').live('click', function () {

		var href = $(this).attr('href')
		if (href == '#') return false

		$('<div></div>')
			.attr('id', 'dialog-add-review')
			.addClass('content')
			.dialog({
				bgiframe: true,
				autoOpen: false,
				height: 300,
				width: 450,
				modal: true,
				title: 'Dodaj opinię',
				buttons: {
					'Zamknij': function() {
						$(this).dialog('close');
					},
					'Dodaj': function () {

						var action = $(this).find('form.form-add-review').attr('action')
						var form_data = $(this).find('form.form-add-review').serialize()

						$.ajax({
							type: 'POST',
							url: action,
							data: form_data,
							container: $(this),
							success: function (result) {
								if (result == 'ok')
								{
									$(this.container).dialog('close')
								}
								else
								{
									$(this.container).empty()
									$(this.container).html(result)
									$('#dialog-add-review').find('.button').remove()
								}
								rank_stars()
							},
							beforeSend: function () {
								//$('input, textarea, select, button', this.container).attr('disabled', 'disabled')
								$(this.container).dialog('disable')
							},
							complete: function () {
								//$('input, textarea, select, button', this.container).removeAttr('disabled')
								$(this.container).dialog('enable')
							}
						})

						return false

					}
				}
			})

		$('#dialog-add-review').load($(this).attr('href'), {}, function () {
			$('#dialog-add-review').find('.button').remove()
			$('#dialog-add-review').dialog('open')
			rank_stars()
		})

		$('#dialog-add-review').find('form.form-add-review').live('submit', function () { return false })

		return false

	})

	$('.breadcrumbs ul li:last-child span.divider').remove()

	if ($('div.login-info #_username').get(0))
	{
		$('div.login-info #_username')
			.data('val', $('div.login-info #_username').val())
			.focus(function () {
				if ($(this).val() == $(this).data('val')) {
					$(this).val('')
				}
			})
			.blur(function () {
				if ($(this).val() == '' || $(this).val() == $(this).data('val')) {
					$(this).val('użytkownik')
				}
			})
	}

	forms_focus()
	rank_stars()
	order_form()

})

function order_form() {

	if ($('#delivery_address_type').is(':checked')) {
		$('fieldset.address-delivery').hide()
	} else {
		$('fieldset.address-delivery').show()
	}

	$('#delivery_address_type').click(function () {
		if ($(this).is(':checked')) {
			$('fieldset.address-delivery').hide()
		} else {
			$('fieldset.address-delivery').show()
		}
	})
	
	if ($('#order_type:not(:checked)').get(0)) {
		$('#order-customer,#order-delivery,#order-payment,#cart-content div.buttons.fast').hide()
	} else {
		$('#order-customer,#order-delivery,#order-payment,#cart-content div.buttons.fast').show()
	}

	$('#order_type').click(function () {
		if ($(this).is(':checked')) {
			$('#order-customer,#order-delivery,#order-payment,#cart-content div.buttons.fast').show()
		} else {
			$('#order-customer,#order-delivery,#order-payment,#cart-content div.buttons.fast').hide()
		}
	})
	
	
	
	$.each($("input[name=payment]"), function() {
		if($(this).is(":checked") && $(this).val() == 5) {
			$("#zagiel-license-container").show();
		}
		$(this).click(function() {
			if($(this).val() == 5) {
				$("#zagiel-license-container").show();
			} else {
				$("#zagiel-license-container").hide();
			}
		});
	});

}

function rank_stars() {

	$('ul.rank').each(function () {
		if ($(this).data('bound') != 'yes') {
			$(this).find('li').each(function () {
				if ($(this).hasClass('on')) {
					$(this).data('status', 'on')
				} else {
					$(this).data('status', 'off')
				}
			})
			$(this).find('li').hover(
				function () {
					var i = $(this).parent().find('li').index(this)
					$(this).parent().find('li').removeClass('on')
					$(this).parent().find('li').slice(0, i+1).addClass('on')
				},
				function () {
					$(this).parent().find('li').removeClass('on')
				}
			)
			$(this).find('li').click(function () {
				var i = $(this).parent().find('li').index(this)
				$(this).parent().find('li').removeClass('on').data('status', 'off')
				$(this).parent().find('li').slice(0, i+1).data('status', 'on').addClass('on')

				$(this).parent().parent().find('input').val($(this).attr('rel'))

			})
			$(this).mouseout(function () {
				$(this).find('li').removeClass('on').each(function () {
					//alert($(this).data('status'))
					if ($(this).data('status') == 'on') { $(this).addClass('on') }
				})

			})
		}
		$(this).data('bound', 'yes')
	})

}

function forms_focus() {

	$('form input, form textarea, form select')
		.focus(function () { $(this).parents('li.field').addClass('focused') })
		.blur(function () { $(this).parents('li.field').removeClass('focused') })

	$('input.button, input[type=button], button, .ui-button').addClass('ui-button ui-state-default ui-corner-all')

	$('.ui-button')
		.live('mouseover', function () {
			$(this).addClass('ui-state-hover')
		})
		.live('mouseout', function () {
			$(this).removeClass('ui-state-hover')
		})

	$('.tooltip_content').each(function () {
		var rel = $(this).attr('rel')
		var t = $(this)

		if (rel != '') {
			var rels = rel.split(' ')

			$(rels).each(function (i, item) {

				var pos = $('#' + item).position()
				var width = $('#' + item).outerWidth()
				var height = $('#' + item).outerHeight()

				$('#' + item).parent().simpletip({
					fixed: true,
					position: [pos.left, pos.top+height+2],
					content: $(t).html()
				})
			})
		}
	})

	/*$('#main-categories ul li.preview').simpletip({
		position: 'right',
		baseClass: 'category-content-tip ui-widget ui-widget-content ui-corner-all',
		content: 'Ładowanie&hellip;',
		onBeforeShow: function () {
			var cls = this.getParent().attr('rel')
			cls = cls.split('-')
			var id = cls[cls.length-1]
			this.load('/kategoria/podglad/' + id, {cache: true})
		}
	})*/

}

function order_user_address_choser() {

	if ($('#delivery_user_address_id option').size() == 0) {
		$('#delivery_user_address_id').parent().parent().parent().hide()
	}
	if ($('#order_user_address_id option').size() == 0) {
		$('#order_user_address_id').parent().parent().parent().hide()
	}

	$.getJSON('/uzytkownik/adresy.json', {}, function (data) {

		if (typeof(data.error) == "undefined")
		{

			$('#delivery_user_address_id').change(function () {
				var id = parseInt($(this).val())
				for (i in data) {
					if (data[i].id == id) {
						$('#delivery_first_name').val(data[i].first_name)
						$('#delivery_last_name').val(data[i].last_name)
						$('#delivery_company_name').val(data[i].company_name)
						$('#delivery_nip').val(data[i].nip)
						$('#delivery_city').val(data[i].city)
						$('#delivery_postal_code').val(data[i].postal_code)
						$('#delivery_address').val(data[i].address)
						$('#delivery_phone').val(data[i].phone)
						$('#delivery_mobile_phone').val(data[i].mobile_phone)
					}
				}
			})

			$('#order_user_address_id').change(function () {
				var id = parseInt($(this).val())
				for (i in data) {
					if (data[i].id == id) {
						$('#order_first_name').val(data[i].first_name)
						$('#order_last_name').val(data[i].last_name)
						$('#order_company_name').val(data[i].company_name)
						$('#order_nip').val(data[i].nip)
						$('#order_city').val(data[i].city)
						$('#order_postal_code').val(data[i].postal_code)
						$('#order_address').val(data[i].address)
						$('#order_phone').val(data[i].phone)
						$('#order_mobile_phone').val(data[i].mobile_phone)
					}
				}
			})

		}

	})

}

function switch_order_payment(id) {

    $.each($("#order-payment ul"), function() {
        if($(this).attr("id") == id) {
            $(this).show();
            $(this).find('.delivery-fr').attr("checked", "checked");

            // aktualizacja kosztu calkowitego
            var subtotal = $('#price-subtotal').eq(0).text();
            cost = $(this).find('.delivery-fr').parent().find('span.cost').eq(0).text();
            total_cost = parseFloat(cost)+parseFloat(subtotal);
            total_cost = Math.round(total_cost*100)/100.0;
            $('#price-total').text(total_cost).effect('highlight', {}, 600);
        } else {
            $(this).hide();
        }
    });

}

function assign_category_form(cid) {
    $('<div id="dialog"></div>').dialog({
        bgiframe: true,
        height: 500,
        width: 800,
        modal: true,
        hide: 'slide',
        close: function() {
            $('#dialog').dialog('destroy');
            $('#dialog').empty().remove();
        }
    }).load($("base").attr("href")+'kategoria/przegladaj/'+cid, {cid:cid}, function() {
        $("#category_list table tr td").each(function() {
            el = $(this).parent().find("input");
            alert(el.length);
            if(el.is(":checked")) el.removeAttr("checked");
            else el.attr("checked", "checked");
        });
    })

}

function assign_category() {

    var ids = Array();
    $("#category_list input[type=checkbox]:checked").each(function() {
        ids[ids.length] = $(this).val();
    });
    var cid = $("#category_filter input[name=cid]").val();

    if(ids.length > 0) {
        $("#category_list").load($("base").attr("href")+'kategoria/przypisz/', {cid:cid,ids:ids.toString()});
    } else {
        alert("Wybierz kategorie do dowi\u0105zania");
    }

}

function filter_category() {

    var filter = $("#category_filter input[name=filter]").val();
    if(filter.length >= 2) {
        $("#category_list").load($("base").attr("href")+'kategoria/filter/', {'filter':filter});
    } else {
        $("#category_list").html("Wpisz min. 2 znaki");
    }
    return false;

}

function obliczRate(koszyk) {
	if (koszyk >= 100) {
		window.open('https://www.eraty.pl/symulator/oblicz.php?numerSklepu=24419751&wariantSklepu=1&typProduktu=0&wartoscTowarow=' + koszyk, 'Policz_rate', 'width=630,height=500,directories=no,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no');
	} else {
		$('<div id="dialog" class="mydialog"></div>').dialog({
			title: 'Informacja',
			modal: true,
			buttons: {
				Ok: function() {
					$(this).dialog('destroy');
				}
			}
		}).html("<p>Aby skorzystać z zakupów na raty wartość towaru musi wynosić minimum 100 złotych.</p>");
	}
}

function kosztyDostawy() {
	$('<div id="dialog" class="mydialog"></div>').dialog({
		height: 450,
		width: 600,
		modal: true,
		title: 'Koszt dostawy',
		buttons: {
			'Zamknij': function() {
				$(this).dialog('destroy');
			}
		}
	}).load($("base").attr("href")+'koszt_dostawy');
}

function przechowalniaInfo() {
	$('<div id="dialog" class="mydialog"></div>').dialog({
		modal: true,
		title: 'Informacja',
		buttons: {
			'Zamknij': function() {
				$(this).dialog('destroy');
			}
		}
	}).html("<p>Aby dodać produkt do przechowalni musisz być zalogowany.</p>");
}
