
/*
 *
 *	global/global.js
 *
 *  Yleiset javascriptit-määritykset
 *  includattu joka sivulle
 *
 *
 *
 */



function addErrorClassToFancy() {
	if($(this).is('.error')) {
		var id = $(this).attr('id');
		$('#'+id+'-button').addClass('error');
	}
}

function helperFormatPrice( price ) {
	var strPrice = price.toFixed(2) + "";
	return strPrice.replace('.',',');
}

function ajaxLoaderGif(id) {
	var img = '<img';
	if(id) {
		img += ' id="'+id+'"';
	}
	img += ' src="'+root_url+'media/img/ajax-loader.gif" class="ajax_loader_gif" alt="'+i18n.loading+'" />';
	return img;
}

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

/**
 * Animoi blinkkiefektin elementtiin
 * @param elem | elementti, jota blinkkaus koskee
 * @param opt | array sisältäen haluttuja ominaisuuksia
 * @return
 */
function blinkit(elem, opt) {
	options = $.extend({
		times: 3,
		duration: 300,
		color: '#E35700'
	}, opt);
	var o_color = elem.css('color');
	if(elem.length) {
		for(i=0; i<options.times; i++) {
			elem.animate({
				color: options.color
			}, options.duration);
			elem.animate({
				color: o_color
			}, options.duration);
		}
	}
}

/**
 * JqueryUi-buttonit
 * alustetaan document readyssa
 */
function buttons() {
	$('.button, button').button();
	$('.button.back').button({icons: {primary: 'ui-icon-arrowthick-1-w'}});
	$('.button.cart').button({icons: {primary: 'ui-icon-cart'}, text: false});
	$('.button.add_to_cart').button({icons: {primary: 'ui-icon-cart', secondary: 'ui-icon-circle-plus'}});
	$('.button.copy_order').button({icons: {primary: 'ui-icon-cart', secondary: 'ui-icon-star'}});
	$('.button.feedback').button({icons: {primary: 'ui-icon-person'}});
	$('.button.delete, button.delete').button({icons: {primary: 'ui-icon-closethick'}});
	$('.button.check').button({icons: {primary: 'ui-icon-check'}});
	$('.button.key').button({icons: {primary: 'ui-icon-key'}});
	$('.button.locked').button({icons: {primary: 'ui-icon-locked'}});
	$('.button.unlock').button({icons: {primary: 'ui-icon-unlocked'}});
	$('.button.plus').button({icons: {primary: 'ui-icon-plus'}});
	$('.button.close').button({icons: {primary: 'ui-icon-closethick'}, text: false});
	$('.button.transfer').button({icons: {primary: 'ui-icon-transferthick-e-w'}});
	$('.button.pencil').button({icons: {primary: 'ui-icon-pencil'}});
	$('.button.dropdown').button({icons: {secondary: 'ui-icon-triangle-1-s'}})
	$('.button.next').button({icons: {secondary: 'ui-icon-circle-arrow-e'}});
	$('.button_set').button().parent().buttonset();
	$('.button.dialog').button({icons: {primary: 'ui-icon-newwin'}});
	$('.button.trash, button.trash').button({icons: {primary: 'ui-icon-trash'}});

	$('.minimalistic_button').button();
	
	$('.guide_items button.close_guide').button({icons: {primary: 'ui-icon-closethick'}, text: false});

	$('.button.dropdown').parent('li').hover(function(){
		$(this).find('.button.dropdown').removeClass('ui-corner-all').addClass('ui-corner-top');
	}, function() {
		$(this).find('.button.dropdown').removeClass('ui-corner-top').addClass('ui-corner-all');
	});
}

/**
 * Funktio, joka liittää laatikon piilotus toiminnon
 */
function close_me() {
	$('.close_me').click(function(e){
		e.preventDefault();
		if($(this).parent('.ui-widget')) {
			$(this).parent().hide();
		}
	});
}

/**
 * Liittää formeille, joilla on class "tips", tooltipin.
 * Triggeri == focus
 * Vain inputeille, joilla on "title"-attribuutti
 * Vaatii jquery.toolsin
 */
function formTips() {
	$('form.tips :input[title]').tooltip({
		position: {
			my: "left+15 center",
			at: "right center",
			collision: "flip fit"
		},
		offset: [-2, 10],
		effect: "fade",
		opacity: 1
	});
}

/**
 * Tarkistaa onko käyttäjän selain IE6
 * @returns {Boolean}
 */
function ie6() {
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
		var ieversion=new Number(RegExp.$1); // capture x.x portion and store as a number
		if (ieversion<7) {
			return true;
		}
	}
	return false;
}

/**
 *
 * @returns
 */
function uiMessageDialog() {
	$(this).dialog({
		resizable: true,
		height: 'auto',
		modal: true,
		buttons: {
			Ok: function() {
				$( this ).dialog( "close" );
			}
		}
	});
}

/**
 * Confirm 20.8.2010
 * Luokka, joka liittää varmistusdialogi-popupin haluttuun painikkeeseen
 * Riippuvuudet: jquery ui-kirjasto
 */
Confirm = $.klass({
	initialize: function(obj, callback, options) {
		this.obj = obj; // painike-elementti
		this.callback = callback; // funktio, jota kutsutaan hyväksyessä

		this.options = {
			uiIcon: 'ui-icon-alert',
			confirmButtonText: 'OK',
			cancelButtonText: 'Peruuta',
			bindClick: true,
			buttons: true,
			width: 300,
			description: false
		};
		this.options = $.extend(this.options, options);
		// painikkeen title-attribuutista sisältö dialogiin
		if(obj.attr('title')) {
			var content = obj.attr('title');
		} else var content = '';
		obj.attr('title', ''); // ettei normaali title tuu näkyviin
		// dialogin otsikko ja body-teksti eroteltuna | -merkillä
		var parts = content.split('|');
		this.title = parts[0];
		if(this.options.description == false) {
			this.description = parts[1];
		} else {
			this.description = this.options.description;
		}

		// kutsutaan dialogin näyttäjää klikatessa painiketta
		if(this.options.bindClick == true) {
			obj.click($.proxy(this.buttonClicked, this));
		}
		return this;
	},
	buttonClicked: function(e) {
		e.preventDefault();
		$(e.currentTarget).removeClass('ui-state-active, ui-state-focus');
		this.show();
	},
	show: function() {
		var div = '<div id="dialogConfirm" class="hidden" title="' + this.title + '">' +
		'<p>';
		if(this.options.uiIcon != false) {
			div += '<span class="ui-icon ' + this.options.uiIcon + '" ' +
				'style="float:left; margin:0 7px 20px 0;"></span>';
		}
		div += this.description + '</p></div>';
		$('body').append(div);

		var buttons = {};
		if(this.options.buttons != false) {
			buttons[this.options.cancelButtonText] = this.cancel;
			buttons[this.options.confirmButtonText] = $.proxy(this.callCallback, this);
		}

		this.buttons = buttons;

		$('#dialogConfirm').dialog({
			resizable: true,
			height: 'auto',
			modal: true,
			buttons: buttons,
			width: this.options.width
		});
		this.decorateButtons('Peruuta', {
			icon: 'ui-icon-cancel'
		});
		this.decorateButtons('Poista', {
			icon: 'white-ui-icon ui-icon-trash',
			classes: 'remove'
		});
	},
	callCallback: function() {
		this.callback(this);
		$('#dialogConfirm').dialog('close');
		$('#dialogConfirm').dialog('destroy');
	},
	cancel: function() {
		$(this).dialog('close');
		$(this).dialog('destroy');
		$('#dialogConfirm').remove();
	},
	decorateButtons: function(containsText, options) {
		var button = $('.ui-dialog-buttonpane')
		    .find('button:contains("' + containsText + '")');

		if(options.icon != '') {

			button.removeClass('ui-button-text-only')
				.addClass('ui-button-text-icon-primary');
		    button.prepend('<span class="ui-button-icon-primary ui-icon ' + options.icon + '"></span>');

		}

		if(options.classes != '') {
			button.addClass(options.classes);
		}
	}

});

/**
 * Confirmin callback
 * @param obj
 */
function deleteConfirmed(obj) {
	window.location = obj.options.href;
}

/**
 * Palaute
 */
var FeedbackDialog = $.klass({
	initialize: function(obj) {
		this.obj = obj;
		this.remote = true;
		this.form = $('#feedbackForm');
		this.obj.click($.proxy(this.clicked, this));

		if(!this.remote) {
			$('#feedbackSend').click($.proxy(this.send, this));
		} else {
			this.remotePostIframe = $('<iframe name="remote_feedback_iframe" id="remoteFeedbackIframe" src="" class="hidden"></iframe>');
			this.remotePostIframe.unbind('load');
			$('body').append(this.remotePostIframe);
			this.form.submit($.proxy(this.remoteFormSubmit, this));
		}

	},
	remoteFormSubmit: function () {
		this.remotePostIframe.unbind('load');
		this.remotePostIframe.load($.proxy(this.iframeReady, this));
		return true;
	},
	clicked: function(e) {
		e.preventDefault();
		e.currentTarget.blur();
		formTips();
		this.show();
	},
	feedbackSentCallback: function(data) {
		$('#feedbackDone').html(data['response']).show();
		if(data['success']) {
			var dialogDiv = this.dialogDiv;
			setTimeout("$('#feedbackDialog').dialog('close'); $('#feedbackSend').button('enable');", 3000);
		} else {
			$('#feedbackSend').button('enable');
		}
	},
	onClose: function(e) {
		// Blurrataan, että tooltip menee piiloon $('.tooltip').hide() <- no go, ei näytä uudelleen
		$('.ui-tooltip').hide();
		//this.form.find('input, textarea').blur();
		$('#feedbackSend').button('enable');
		$('#feedbackDone').html('');
	},
	clearInputs: function() {
		$('#feedbackForm').find('input,textarea').each(function(){
			$(this).val('');
		});
	},
	iframeReady: function () {
		this.feedbackSentCallback({
			'response': this.getSuccessResponse('Kiitos yhteydenotostasi.'),
			'success': 'true'
		});
	},
	getSuccessResponse: function (message) {
		var html = '<div class="ui-widget">';
		html += '<div class="ui-state-highlight ui-corner-all" style="margin-top: 20px; padding: 0 .7em;">';
			html += '<p style="padding: 10px">';
			html += '<span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>';
			html += message;
			html += '</p>';
		html += '</div>';
		html += '</div>';
		return html;
	},
	send: function(e) {
		e.preventDefault();
		// estä tuplaklikkaus
		$('#feedbackSend').button('disable');

		$.post(this.form.attr('action'), {
			url: $('#feedbackUrl').val(),
			email: $('#feedbackEmail').val(),
			title: $('#feedbackTitle').val(),
			message: $('#feedbackMessage').val()
		}, $.proxy(this.feedbackSentCallback, this), "json");

	},
	sendIframe: function () {
		this.remotePostIframe.load($.proxy(this.iframeReady, this));
	},
	show: function() {
		this.dialogDiv = $('#feedbackDialog');
		this.dialogDiv.dialog({
			resizable: true,
			height: 'auto',
			width: 650,
			minWidth: 300,
			modal: true,
			close: $.proxy(this.onClose, this),
			title: this.obj.text()
		});
		if(ie6()) {
			this.dialogDiv.dialog('option', 'minHeight', 600);
		}
		$('#feedbackEmail').focus().focus();
	}
});

/**
 * Poistettaville itemeille konfirmointi
 */
function init_confirm_delete() {
	// painike, josta halutaan varmistus dialogi
	var deleteElement = $('.confirm_delete');
	if(deleteElement.length) {
		deleteElement.each(function(e){
			e.preventDefault;
			var href = $(this).attr('href');
			var confirm = new Confirm($(this), deleteConfirmed, {
				href: href,
				uiIcon: 'ui-icon-alert',
				confirmButtonText: 'Poista'
			});
		});
	}
}

/**
 * Toglaa bindatun .toggle_form_checkboxes-elementin formissa olevat
 * muut checkboxit
 */
function toggleFormCheckBoxes(e) {
	var $this = $(e.currentTarget);
	var $form = $this.closest('form');
	if($this.is(':checked')) {
		$form.find('input[type=checkbox]:not(.toggle_form_checkboxes)').each(function(){
			//console.log($(this));
			$(this).attr('checked', true);
		});
	} else {
		$form.find('input[type=checkbox]:not(.toggle_form_checkboxes)').each(function(){
			$(this).attr('checked', false);
		});
	}
}

//a custom format option callback
var nameDescriptionFormat = function(text){
	var newText = text;
	//array of find replaces
	var findreps = [
		{find:/^([^\-]+) \- /g, rep: '<span class="ui-selectmenu-item-header">$1</span>'},
		{find:/([^\|><]+) \| /g, rep: '<span class="ui-selectmenu-item-content small_text">$1</span>'},
		{find:/([^\|><\(\)]+) (\()/g, rep: '<span class="ui-selectmenu-item-content">$1</span>$2'},
		{find:/([^\|><\(\)]+)$/g, rep: '<span class="ui-selectmenu-item-content small_text">$1</span>'},
		{find:/(\([^\|><]+\))$/g, rep: '<span class="ui-selectmenu-item-footer">$1</span>'}
	];

	for(var i in findreps){
		newText = newText.replace(findreps[i].find, findreps[i].rep);
	}
	return newText;
};

/**
 * @see http://james.padolsey.com/javascript/regex-selector-for-jquery/
 */
jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ?
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

function bindMenuJqueryUiEvents() {
	$('.main_menu li a').hover(
		function(){
			if(!$(this).is('.ui-state-active')) {
				$(this).addClass("ui-state-hover");
			} else {
				$(this).removeClass("ui-state-hover");
			}
		},
		function(){
			$(this).removeClass("ui-state-hover");
		}
	);

}

var ActiveCart = $.klass({
	initialize: function (element) {
		this.element = element;
		this.data = null;
		if(this.element) {
			this.loadData();
		}
	},
	dataLoaded: function (data) {
		this.data = data;
		this.reloadHtml();
	},
	loadData: function () {
		$.post(root_url+'webink_ajax/active_cart_data',{},$.proxy(this.dataLoaded, this),"json");
	},
	reloadHtml: function () {
		this.element.html(this.data.count);
	}
});

var feedbackDialogInstance;

/**
 * Document ready
 */
$(function(){

	if($('#activeCart').length) {
		new ActiveCart($('#activeCart'));
	}

	bindMenuJqueryUiEvents();

	if(ie6()) {
		$('body').append('<div class="ui-widget-overlay"></div>');
	}

	buttons();
	$('#tabs').tabs();
	$('.fancy_select').each(addErrorClassToFancy);

	$('.button.ui-corner-bottom-only').removeClass('ui-corner-all').addClass('ui-corner-bottom');

	init_confirm_delete();

	// Lisätään jokaiselle ilmoitukselle "sulje"-painike, jolla laatikko menee heti kiinni
	$(".closable_box").each(function(){
		if(!$(this).is('.ui_message_popup')) {
			$(this).find('div').append('<a href="" class="button close close_me floatr">Sulje</a>');
			$('.button.close').button({icons: {primary: 'ui-icon-closethick'}, text: false});
			$('.close_me').click(function(e){
				e.preventDefault();
				if($(this).parents('.ui-widget')) {
					if($(this).parents('.box')) {
						$(this).parents('.box').remove();
					}
					$(this).parents('.ui-widget').remove();
				}
			});
		}
	});

	// Tuotelistauksen hintaesimerkkien vertical-keskitys
	$('.product_item_prices').each(function(){
		marginTop = $(this).height()/-2;
		$(this).css('margin-top', marginTop+'px')
	});

	$('select.name_description_format').selectmenu({
		style: 'dropdown',
		width: 200,
		format: nameDescriptionFormat
	});

	$('select.fancy_select').selectmenu({
		style: 'dropdown',
		width: 200,
		transformClasses: true
	});

	$('.ui_message_popup').each(uiMessageDialog);

	$('a.toggle_next_ul').hover(function(){
		$(this).next('ul').show();
	},function(){
		$(this).next('ul').hide();
	});

	feedbackDialogInstance = new FeedbackDialog($('#showFeedbackForm'));

	$('.tipme[title!=""]').tooltip({
		position: {
			my: "left+15 center",
			at: "right center",
			collision: "flip fit"
		},
		effect: 'fade'
	});
	$('.tipme_delay[title!=""]').tooltip({
		position: {
			my: "left+15 center",
			at: "right center",
			collision: "flip fit"
		},
		effect: 'fade'
	});
	$('.tipme_delay_product_option[title!=""]').tooltip({
		position: {
			my: "left center",
			at: "center top",
			collision: "flip fit",
			offset: "10 -30"
		},
		effect: 'fade'
	});

	$('.datepicker').each(function(){
		attachDatePicker($(this));
	});
	$('.datepicker_range').each(function(){
		attachRangeDatePicker($(this));
	});

	$('.toggle_div[rel]').click(function(){
		$('.'+$(this).attr('rel')).slideToggle();
	});

	$('.toggle_form_checkboxes').click(toggleFormCheckBoxes);

});

/**
 * DATEPICKER JA LOCALISOINNIT
 * ---------------------------
 * @param elem
 */
function attachDatePicker(elem) {
	$.datepicker.setDefaults( $.datepicker.regional[ "" ] );
	// Default-asetukset datepickerille
	var options = {
		changeMonth: true,
		changeYear: true,
		maxDate: '-0d',
		minDate: '-110y',
		yearRange: '-110:+0'
	}
	// Yhdistetään regional-asetukset defaultteihin
	var optionsWithRegional = $.extend($.datepicker.regional[site_lang], options);
	elem.datepicker( optionsWithRegional ); // datepicker !
}
var rangeDates;
function attachRangeDatePicker(elem) {
	$.datepicker.setDefaults( $.datepicker.regional[ "" ] );
	// Default-asetukset datepickerille
	var options = {
		changeMonth: true,
		changeYear: true,
		maxDate: '-0d',
		minDate: '-110y',
		numberOfMonths: 3,
		yearRange: '-110:+0',
		onSelect: rangeDatePickerSelected
	}
	// Yhdistetään regional-asetukset defaultteihin
	var optionsWithRegional = $.extend($.datepicker.regional[site_lang], options);
	rangeDates = elem.datepicker( optionsWithRegional ); // datepicker !
}
function rangeDatePickerSelected ( selectedDate ) {
	var option = this.id == "dateFrom" ? "minDate" : "maxDate",
		instance = $( this ).data( "datepicker" ),
		date = $.datepicker.parseDate(
			instance.settings.dateFormat ||
			$.datepicker._defaults.dateFormat,
			selectedDate, instance.settings );
	rangeDates.not( this ).datepicker( "option", option, date );
}
/* Finnish initialisation for the jQuery UI date picker plugin. */
/* Written by Harri Kilpi� (harrikilpio@gmail.com). */
jQuery(function($){
    $.datepicker.regional['fi-fi'] = {
		closeText: 'Sulje',
		prevText: '&laquo;Edellinen',
		nextText: 'Seuraava&raquo;',
		currentText: 'T&auml;n&auml;&auml;n',
        monthNames: ['Tammikuu','Helmikuu','Maaliskuu','Huhtikuu','Toukokuu','Kes&auml;kuu',
        'Hein&auml;kuu','Elokuu','Syyskuu','Lokakuu','Marraskuu','Joulukuu'],
        monthNamesShort: ['Tammi','Helmi','Maalis','Huhti','Touko','Kes&auml;',
        'Hein&auml;','Elo','Syys','Loka','Marras','Joulu'],
		dayNamesShort: ['Su','Ma','Ti','Ke','To','Pe','Su'],
		dayNames: ['Sunnuntai','Maanantai','Tiistai','Keskiviikko','Torstai','Perjantai','Lauantai'],
		dayNamesMin: ['Su','Ma','Ti','Ke','To','Pe','La'],
		weekHeader: 'Vk',
        dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''
		};
    $.datepicker.setDefaults($.datepicker.regional['fi-fi']);
});
/* Swedish initialisation for the jQuery UI date picker plugin. */
/* Written by Anders Ekdahl ( anders@nomadiz.se). */
jQuery(function($){
    $.datepicker.regional['se'] = {
		closeText: 'Stäng',
        prevText: '&laquo;Förra',
		nextText: 'Nästa&raquo;',
		currentText: 'Idag',
        monthNames: ['Januari','Februari','Mars','April','Maj','Juni',
        'Juli','Augusti','September','Oktober','November','December'],
        monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
        'Jul','Aug','Sep','Okt','Nov','Dec'],
		dayNamesShort: ['Sön','Mån','Tis','Ons','Tor','Fre','Lör'],
		dayNames: ['Söndag','Måndag','Tisdag','Onsdag','Torsdag','Fredag','Lördag'],
		dayNamesMin: ['Sö','Må','Ti','On','To','Fr','Lö'],
		weekHeader: 'Ve',
        dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''
		};
    $.datepicker.setDefaults($.datepicker.regional['se-se']);
});
