var card = null;
var lock_product_selection = false;
var ie6 = $.browser.msie && $.browser.version < 7;

var loc_urls = {'fi' : '/pehmea_tuotetiedot_ajax', 'se' : '/pehmea_tuotetiedot_ajax_se'};
var loc_payment = {'fi' : '/pehmea_maksutapa FORM', 'se' : '/mjukispaketet_betalningssatt FORM'};
var loc_info = {'fi' : 'Lisätietoa tuotteesta', 'se' : 'Info'};
var loc_buy = {'fi' : 'Osta tuote', 'se' : 'Lägg i korgen'};
var loc_add = {'fi' : 'Lisää', 'se' : 'Lägg i korgen'};
var loc_remove = {'fi' : 'Poista', 'se' : 'Ta bort'};
var loc_confirm = {'fi' : 'OK', 'se' : 'OK'};
var loc_close = {'fi' : 'Sulje', 'se' : 'Stäng'};
var loc_card = {'fi' : 'Valitse korttipohja', 'se' : 'Välj kortbotten'};
var loc_product = {'fi' : 'Valitse vähintään yksi tuote', 'se' : 'Välj åtminstone en produkt'};
var loc_message = {'fi' : 'Kirjoita viesti tekstikenttään', 'se' : 'Var god och skriv ett meddelande.'};
var loc_allfields = {'fi' : 'Ole hyvä ja täytä kaikki tiedot.', 'se' : 'Var god och fyll i alla fält.'};


var uniq;

var lang = $('body').attr('class');  // potential bug here

$(function() {

	if (ie6) {
		$('.company-product-listing LI').hover(function() {		
			$(this).addClass('hover');
		}, function() {
			$(this).removeClass('hover');		
		});
	}

	$('.company-product-listing LI').click(function(e) {
		e.preventDefault();
		var pid = $(this).attr('id').split('-')[1];
		popup_show(loc_urls[lang] + '?id=' + pid);
	}).attr('title', loc_info[lang]);

	var bought_idx = 0;
	$('.company-product-listing LI .buy-first').click(function(e) {
		if ($(this).hasClass('buy-first')) {
			buy_item(1, this);
			$(this).parents('li:first').addClass('index-' + bought_idx++);
		}
		e.stopPropagation();
		e.preventDefault();
	}).attr('title', loc_buy[lang]);

	$('.company-product-listing LI .buy-more').click(function(e) {
		buy_item(1, this.parentNode);	
		e.stopPropagation();
		e.preventDefault();
	}).hover(function() {
		$(this.parentNode).addClass('hover-more');
	}, function() {
		$(this.parentNode).removeClass('hover-more');	
	}).attr('title', loc_add[lang]);

	$('.company-product-listing LI .buy-less').click(function(e) {
		buy_item(-1, this.parentNode);	
		e.stopPropagation();
		e.preventDefault();
	}).hover(function() {
		$(this.parentNode).addClass('hover-less');
	}, function() {
		$(this.parentNode).removeClass('hover-less');	
	}).attr('title', loc_remove[lang]);
	
	$('.tab-nav .next').click(function() {
		var current = $('#tabbed .tab:visible');
		var next = current.next();
		if (validate_tab(current.prevAll('.tab').length)) {
			if (next.length > 0) {

	var items = $('.company-product-listing .selected');
	var ilist = "";

	items.sort(function(a, b) {
		return parseInt($(a).class_attr('index')) > parseInt($(b).class_attr('index')) ? 1 : -1;
	}).each(function(i) {
		ilist += $(this).attr('id').split('-')[1] + ",";
	});
$('#pictures').load('/pehmea-tuotekuvat-ajax?ilist='+ilist);


				current.hide();
				next.show();
				update_tab_num();
			} else {
				// final action
				$('#company-payment FORM').submit();				
			}
		}
	});

	$('.tab-nav .prev').click(function() {
		var current = $('#tabbed .tab:visible');
		var prev = current.prev();
		if (prev.length > 0) {
			current.hide();
			prev.show();
			update_tab_num();
		}
	});
	
	$('#company-card-customization INPUT[type=checkbox]').attr('disabled', true);
	$('#company-card-selection DIV').click(function() {
		$(this).addClass('selected').siblings().removeClass('selected');
		$(this).removeClass('unselected').siblings().addClass('unselected');
		$('#company-card-customization .preview').removeClass('disabled');
		$('#company-card-customization :input').attr('disabled', false);
		$('#company-card-customization INPUT:visible:first').focus();
		$('#company-card-customization .preview .img').css('backgroundImage', $(this).css('backgroundImage'));

		if ($(this).attr('class') == "preview theme-default-1 selected" || $(this).attr('class') == "preview theme-default-2 selected") {
			$('#custom-head-fi').val("Pehmeä paketti");
			$('#custom-msg-fi').val("Olet saanut lahjaksi UNICEFin Pehmeän Paketin. Se on aito lahja, joka varmistaa elintärkeiden tarvikkeiden pääsyn niitä tarvitseville lapsille ympäri maailman.");
			$('#custom-head-se').val("Mjukispaket");
			$('#custom-msg-se').val("Du har fått UNICEFs Mjukispaket. Den här äkta gåvan möjliggör att livsviktiga förnödenheter når barn som behöver dem runtom i världen.");
			$('#custom-head-en').val("Inspired gift");
			$('#custom-msg-en').val("You have received UNICEF's Inspired gift! Inspired Gifts are real life-saving gifts that are distributed to children and their communities around the world.");
		}

		if ($(this).attr('class') == "preview theme-blue-1 selected" || $(this).attr('class') == "preview theme-blue-2 selected") {
			$('#custom-head-fi').val("Onneksi olkoon!");
			$('#custom-msg-fi').val("Olet saanut lahjaksi UNICEFin Pehmeän Paketin. Se on aito lahja, joka varmistaa elintärkeiden tarvikkeiden pääsyn niitä tarvitseville lapsille ympäri maailman.");
			$('#custom-head-se').val("Gratulerar!");
			$('#custom-msg-se').val("Du har fått UNICEFs Mjukispaket. Den här äkta gåvan möjliggör att livsviktiga förnödenheter når barn som behöver dem runtom i världen.");
			$('#custom-head-en').val("Congratulations!");
			$('#custom-msg-en').val("You have received UNICEF's Inspired gift! Inspired Gifts are real life-saving gifts that are distributed to children and their communities around the world.");
		}

		if ($(this).attr('class') == "preview theme-red-1 selected" || $(this).attr('class') == "preview theme-red-2 selected") {
			$('#custom-head-fi').val("Hyvää Joulua!");
			$('#custom-msg-fi').val("Olet saanut lahjaksi UNICEFin Pehmeän Paketin. Se on aito lahja, joka varmistaa elintärkeiden tarvikkeiden pääsyn niitä tarvitseville lapsille ympäri maailman.");
			$('#custom-head-se').val("God Jul!");
			$('#custom-msg-se').val("Du har fått UNICEFs Mjukispaket. Den här äkta gåvan möjliggör att livsviktiga förnödenheter når barn som behöver dem runtom i världen.");
			$('#custom-head-en').val("Merry Christmas!");
			$('#custom-msg-en').val("You have received UNICEF's Inspired gift! Inspired Gifts are real life-saving gifts that are distributed to children and their communities around the world.");
		}
save_card();
	});
	
	$('#company-card-customization .custom-msg').focus(function() {
		$('#company-card-selection .selected .hilite-msg').removeClass('hidden');
	}).blur(function() {
		$('#company-card-selection .selected .hilite-msg').addClass('hidden');
	});

	$('#company-card-customization [name=logo]').focus(function() {
		$('#company-card-selection .selected .hilite-logo').removeClass('hidden');
	}).blur(function() {
		$('#company-card-selection .selected .hilite-logo').addClass('hidden');
	});
	
	$('#company-card-customization .enable-msg')
		.click(function() { toggle_msg(this) })
		.each(function() { toggle_msg(this) });
		
	$('#company-card-form').submit(function() {		
		save_card(function() {
			load_payment_form();
		});
		return false;
	});
		
	$('#company-card-customization .preview A').click(function(e) {
	e.preventDefault();
var that = this;
		var urls = {
			fi: ['/e-kortti', '/pdf-kortti'],
			se: ['/e-kort', '/pdf-kort'],
			en: ['/e-card', '/pdf-card'] }
		var lang = $(this).parents('FIELDSET:first').attr('lang');
		var url = urls[lang][$(this.parentNode).hasClass('preview-pdf') ? 1 : 0];
		save_card();
	window.open(url + '?k=' + card.uniq, 'preview','toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes,status=no');

	/*
		save_card(function() {
$(that).attr('href', url + '?k=' + $('input[name=uniq]').val());
window.location = url + '?k=' + card.uniq;
		});*/


	});
		
	$(window).keyup(function(e) {
		if (e.keyCode == 27)
			popup_close();
	});

	update_tab_num();
});

var Card = function(cb) {
	var that = this;
	$.post('/company-create-card-ajax', {
		'ngform_on': 1,
		'ngf_okparams': 'pid=%{ngform_pid}&uniq=%{ngf_uniq}',
		'q0': 1,
		'q1': $('body').hasClass('fi') ? 'suomi' : 'ruotsi'
	}, function(data, status) {
		var retval = $.trim(data).split(' ');
		that.pid = retval[0];
		that.uniq = retval[1];
		$.cookie('ppcart', that.uniq, { path: '/' });
		that.save(cb);
	});
}

Card.prototype.save = function(cb) {
	// Ajax-emulation using iframe
	var that = this;
	var form = $('#company-card-form');
	var theme = get_selected_theme();
	if (theme) {
		$('[name=cmf_pids]', form).val(this.pid);
		$('[name=uniq]', form).val(this.uniq);
uniq = this.uniq;
		$('#input-theme').val(theme);
		$(form).ajaxSubmit(
			{ success: function() {
				that.add_items(cb);
			}, error: function(xhr, status, error) {
				crash();
			}, iframe: true
		});
	} else {
		alert(loc_card[lang]);
	}
}

Card.prototype.add_items = function(cb) {
	if (this.items_added) {
		window.setTimeout(cb, 0);
		return false;
	}
	var that = this;
	var params = { cmf_op: 'add' };
	var items = $('.company-product-listing .selected');
	items.sort(function(a, b) {
		return parseInt($(a).class_attr('index')) > parseInt($(b).class_attr('index')) ? 1 : -1;
	}).each(function(i) {
		params['cmf_' + i + '_0'] = that.uniq;  // ostoskori
		params['cmf_' + i + '_4'] = $.trim($('.count .value', this).text());  // kpl 
		params['cmf_' + i + '_7'] = $(this).attr('id').split('-')[1];  // tuote
	});
	$.post('/company-card-add-item-ajax', params, function(data, status) {
		if ($.trim(data).indexOf('OK') == 0) {
			that.items_added = true;
			window.setTimeout(cb, 0);
		} else {
			crash();
		}
	});
}

function save_card(cb) {
	if (! card) {
		card = new Card(cb);
	} else {
		card.save(cb);
	}
}

function crash() {
	alert('Valitettavasti palvelussa tapahtui virhe.');
}

function get_selected_theme() {
	var selected = $('#company-card-selection .selected');	
	return selected.length > 0 ? selected[0].className.match(/theme-([a-z]+)-(1|2)/)[1] + "-" + selected[0].className.match(/theme-([a-z]+)-(1|2)/)[2] : false;
}

function update_tab_num() {
	var total = $('#tabbed .tab').length;
	//var total = 3;
	var current = $('#tabbed .tab:visible').prevAll().length + 1;
	$('.tab-nav .current').text(current + '/' + total);
}

function update_total_price() {
	var total = 0;
	$('.company-product-listing LI.selected').each(function() {
		var price = parseInt($('.price', this).text());
		var count = parseInt($('.count .value', this).text());
		total += price * count;
	});
	$('.total-price').css('visibility', total > 0 ? 'visible' : 'hidden').find('.value').text(total);
}

function toggle_msg(checkbox) {
	$('.toggleable', $(checkbox).parents('FIELDSET:first'))
		[checkbox.checked ? 'removeClass' : 'addClass']('hidden').focus();
}

function validate_tab(index) {
	if (index == 0) {
		if ($('.company-product-listing .selected').length == 0) {
			alert(loc_product[lang]);
			return false;
		} else {
			/*if (! confirm('Olet ostamassa tuotteita ' + $('#total-price .value').text() + ' eurolla. Jatketaanko?'))
				return false;*/
		}
		lock_product_selection = true;
	}
	if (index == 1) {
		var invalid = $('.required:input').removeClass('invalid')
			.filter('[value=]').addClass('invalid');
		if (invalid.length > 0) {
			alert(loc_allfields[lang]);
			invalid[0].focus();
			return false;
		}
		/* Viesti pakolliseksi
		var foo = '';
		$('.custom-msg').each(function(i){ foo += this.value });
		if(!foo) {
                  alert(loc_message[lang]);
                  return(false);
		}
		*/
                if($('#company-card-selection .selected').size() == 0) {
                  alert(loc_card[lang]);
                  return(false);
                }
		$('#company-card-form').submit();
	}
	return true;
}

function popup_show(url) {
	var p = $('#popup');
	if (p.length == 0) {
		p = $('<div id="popup"><a href="#close" class="close">'+loc_close[lang]+'</a><div class="content"><img class="loading" src="/files/unicef/pehmea_gfx/loading.gif" alt="" /></div><a href="#close" class="close-text">'+loc_close[lang]+'</a></div>');
		p.appendTo('#content');
		$('[href$=#close]', p).click(function(e) {
			e.preventDefault();
			popup_close();
		}).attr('title', loc_close[lang]);
	}
	p.css('top', ie6 ? 500 : ($(window).scrollTop() + 20))
		.css('left', ($(document).width() - $(p).outerWidth()) / 2 + 30)
		.show()
		.find('.content')
		.empty()
		.load(url, null, function(text, status, xhr) {
			$('.gallery .thumbs A', this).click(function(e) {
				e.preventDefault();
				var g = $(this).parents('.gallery:first');
				$('.fulls [src="' + $(this).attr('href') + '"]', g)
					.removeClass('hidden')
					.siblings().addClass('hidden');
				$(this).addClass('selected').siblings().removeClass('selected');
			}).eq(0).click();
			$('.addtobasket FORM', p).submit(function() {
				var icon = $('#product-' + $('.addtobasket [name=pid]').val() + ' .count');
				var amount = $('.addtobasket .amount', p).val();
				buy_item(amount, icon);
				popup_close();
				return false;
			});
		});
		if (ie6) window.location.href = window.location.href.replace(/(#.*)?$/, '#popup');
}

function popup_close() {
	$('#popup').hide();
}

function buy_item(delta, elem) {
	if (card && card.items_added) {
		if (confirm('Lahjavalintojen muokkaus on mahdollista vain tyhjentämällä nykyiset valinnat ja aloittamalla alusta. Aloitetaanko alusta?')) {
			window.location.reload();
		}
		return false;
	}
	var count = $('.value', elem);
	var value = count.text();
	var new_value = parseInt(value || 0) + parseInt(delta);
	if (new_value >= 0) {
		count.text(new_value);
		$(elem)[new_value > 0 ? 'removeClass' : 'addClass']('buy-first');
		$(elem).parents('LI:first')[new_value > 0 ? 'addClass' : 'removeClass']('selected');
		update_total_price();
	}
}

function load_payment_form() {
	$('#company-payment').load(loc_payment[lang]);
}


/* Parse pseudo-attribute from element's class.
  If class="name1-value1 name2-value2", then .class_attr('name1') returns 'value1'. */
jQuery.fn.extend({
	class_attr: function(attr) {
		if (this[0]) {
			var m = this[0].className.match(new RegExp(attr + '-([^ ]+)'));
			if (m && m[1]) return m[1];
		}
		return false;
	}
});


jQuery.fn.sort = function() {  
   return this.pushStack( [].sort.apply( this, arguments ), []);  
 };


/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie=function(a,b,c){if(typeof b!='undefined'){c=c||{};if(b===null){b='';c.expires=-1}var d='';if(c.expires&&(typeof c.expires=='number'||c.expires.toUTCString)){var e;if(typeof c.expires=='number'){e=new Date();e.setTime(e.getTime()+(c.expires*24*60*60*1000))}else{e=c.expires}d='; expires='+e.toUTCString()}var f=c.path?'; path='+(c.path):'';var g=c.domain?'; domain='+(c.domain):'';var h=c.secure?'; secure':'';document.cookie=[a,'=',encodeURIComponent(b),d,f,g,h].join('')}else{var j=null;if(document.cookie&&document.cookie!=''){var k=document.cookie.split(';');for(var i=0;i<k.length;i++){var l=jQuery.trim(k[i]);if(l.substring(0,a.length+1)==(a+'=')){j=decodeURIComponent(l.substring(a.length+1));break}}}return j}};

