/**
 * @framework:	CFF - Classy Frontend Framework
 * @author:		Angelo Dini
 * @copyright:	http://www.divio.ch under the BSD Licence
 * @requires:	Classy, jQuery
 *
 * check if classy.js and Cl namespace exists */
 window.Class = window.Class || {};
 var Cl = window.Cl || {};

/*##################################################|*/
/* #CUSTOM APP# */
jQuery(document).ready(function ($) {
	/**
	 * Browser helpers
	 * @version: 0.1.1
	 */
	Cl.Browser = {
		init: function () {
			// initiate ie6 fixes
			if(!window.XMLHttpRequest) this.ie6();
			if(navigator.userAgent.match(/Mobile/i)) this.mobile();
		},
		ie6: function () {
			// add pseudo fixes
			$.fn.fix_pseudos = function() {
				this.filter(":first-child").addClass("first-child");
				this.filter(":last-child").addClass("last-child");
			};
		},
		mobile: function () {
			// pan to the bottom, hides the location bar
			setTimeout(function () {
				window.scrollTo(0, 1);
			}, 100);

			// attach hover events
			$('a').bind('touchstart', function () { $(this).addClass('hover'); });
			$('a').bind('touchend', function () { $(this).removeClass('hover'); });
		}
	};
	// autoinit
	Cl.Browser.init();
	
	/**
	 * Base initial class
	 */
	Cl.Base = {
		init: function () {
			// log('hello world');
		}
    };
	// autoinit
	Cl.Base.init();

	Cl.Basket = {
		init: function () {
			var that = this;

			this.container = $('.tbl_basket');
			this.rows = this.container.find('.calcrow');
			this.rows.each(function (index, item) {
				that.setup.call(that, $(item));
			});

			this.calculateTotal();

			this.billing();
			this.country();
		},

		setup: function (row) {
			var that = this;
			var input = row.find('.input_text-amount');
				input.bind('change', function (e) {
					// insure to get the new value when its changes
					setTimeout(function () {
						that.calculate.call(that, row);
						that.calculateTotal.call(that);
					}, 100);
				});

			this.calculate(row);

			// attach events to rows
			this.counter(row, '.countfield .arrow-up', '.countfield .arrow-down');
		},

		counter: function (container, arrowup, arrowdown) {
			var that = this;
			// js for count
			container.find(arrowup).bind('click', function (e) {
				e.preventDefault();
				var input = container.find('.input_text-amount');
				var current = input.val();
				input.val(1);
				input.trigger('change');
				if(container.find('.frm_ajax').length) that.ajaxSend(container);
				input.val(parseInt(current) + 1);
			});

			container.find(arrowdown).bind('click', function (e) {
				e.preventDefault();
				var input = container.find('.input_text-amount');
				var current = input.val();
				if(current <= 0) return false;
				input.val(-1);
				input.trigger('change');
				if(container.find('.frm_ajax').length) that.ajaxSend(container);
				input.val(parseInt(current) - 1);
			});
		},

		ajaxSend: function (container) {
			var form = container.find('.frm_ajax');

			$.ajax({
				'type': 'POST',
				'url': form.attr('action'),
				'data': form.serialize(),
				'success': function (data) {
					if(data.error) {
						window.location.reload();
					}
				}
			});
		},

		calculate: function (row) {
			var count = row.find('.input_text-amount').val();
			var price = row.find('.price-item').text();

			row.find('.price-rowtotal').text(parseInt(count) * parseInt(price));
		},

		calculateTotal: function () {
			// calculate total
			var total = this.container.find('.pice-total');
			var price = 0;
			var prices = this.container.find('.price-rowtotal');
				prices.each(function (index, item) {
					price += parseInt($(item).text());
				});

			total.text(price);
		},

		billing: function () {
			var container = $('.additional');
			var trigger = $('.additional-trigger input');
				trigger.bind('change', function (e) {
					var target = $(e.currentTarget);
					if(target.is(':checked')) {
						container.css('opacity', 0.4);
						container.find('input').each(function (index, item) {
							$(item).attr('disabled', 'disabled');
						});
					} else {
						container.css('opacity', 1);
						container.find('input').each(function (index, item) {
							$(item).removeAttr('disabled');
						});
					}
				});

				trigger.trigger('change');
		},

		country: function () {
			var option = $('.id_bill-payment_method_1');
			var field = $('#id_bill-country');
				field.bind('change', function (e) {
					if(field.val() !== 'CH') {
						option.css('opacity', 0.4);
						option.find('input').attr('disabled', 'disabled');
					} else {
						option.css('opacity', 1);
						option.find('input').removeAttr('disabled');
					}
				});

				field.trigger('change');
		}
	};
	if($('.tbl_basket').length) Cl.Basket.init();
// prevent conflicts
});

/**
 * JQUERY CUSTOM PLUGINS
 * ##################################################|
 */
jQuery(document).ready(function ($) {
	/**
	 * Target modifier
	 * @version: 0.3.2
	 * @param: property (target:blank)
	 * @example: <a href="#" rel="target:blank">Lorem Ipsum</a>
	 */
	$.fn.defineTarget = function (options) {
		options = $.extend({ property: 'rel' }, options);
		return this.each(function () {
			// catch error if no property is set
			if($(this).attr(options.property) === undefined) return false;
			$(this).attr('target', '_' + $(this).attr(options.property).split(':')[1]);
		});
	};
	$('a[rel*="target:"]').defineTarget();
	$('a[class*="target:"]').defineTarget({ property: 'class' });

	/**
	 * E-Mail encrypte
	 * @version: 0.3.2
	 * @param: autoConvert (converts innerhtml to match the email address)
	 * @example: <a href="#info" rel="divio.ch" class="mailcrypte">E-Mail</a>
	 */
	$.fn.mailCrypte = function (options) {
		options = $.extend({
			autoConvert: true
		}, options);

		return this.each(function () {
			var mailto = 'mailto:' + $(this).attr('href').replace('#', '') + '@' + $(this).attr('rel');
			$(this).attr('href', mailto);
			if(options.autoConvert) $(this).html(mailto.replace('mailto:', ''));
		});
	};
	$('a.mailcrypte').mailCrypte({ autoConvert: true });

	/**
	 * Pop-Up Generator
	 * @version: 0.2.2
	 * @param: width (initial width)
	 * @param: height (initial height)
	 * @example: <a href="http://www.google.ch" class="popup">Open Pop-Up</a>
	 */
	$.fn.autoPopUp = function (options) {
		options = $.extend({ width: 750, height: 500}, options);
		var size = { 'x': options.width, 'y': options.height };
		
		return this.each(function () {
			var url = $(this).attr('href');
			// attach event
			$(this).bind('click', function (e) {
				e.preventDefault();
				window.open(url, '_blank', 'width=' + size.x + ',height=' + size.y + ',status=yes,scrollbars=yes,resizable=yes');
			});
		});
	};
	//$('.popup').autoPopUp();

	/**
	 * Auto input fill-in
	 * @version: 0.6.1
	 * @param: label (if true than labeltext on parent else rel attribut on this)
	 * @param: strip (replacement text)
	 * @param: add (add additional information)
	 */
	$.fn.fieldLabel = function (options) {
		options = $.extend({
			label: true,
			strip: '',
			add: ''
		}, options);

		// show functionality
		function show(el, label) {
			if(el.attr('value') != '') return false;
			el.attr('value', label);
			return true;
		}

		// hide functionality
		function hide(el, e, label) {
			if(e.type == 'blur' && el.attr('value') == label) return false;
			el.attr('value', '');
			return true;
		}

		return this.each(function () {
			// store label element and use replacement
			var label = (options.label) ? $(this).parent().find('label').text() : $(this).attr('rel');
			label = label.replace(options.strip, '');
			label += options.add;

			// initialize
			if($(this).attr('value') == '') $(this).attr('value', label);

			// attach event
			$(this).bind('click', function (e) {
				if($(this).attr('value') == label) hide($(this), e, label)
			});
			$(this).bind('blur', function (e) {
				($(this).attr('value') == label) ? hide($(this), e, label) : show($(this), label);
			});
		})
		
	};
	//$('.fieldLabel').fieldLabel({ strip: ': ', add: '...' });

	/**
	 * Collapser/expander
	 * @version: 0.3.2
	 * @param: show (is element initially shown)
	 * @param: fx (animation, either toggle, fade or slide)
	 * @param: event (event.hover and event.blur)
	 * @param: timeout (timeout till event triggers off)
	 * @param: triggerClass (anchor element that triggers functionality)
	 * @param: containerClass (element that will be triggered)
	 * @param: activeClass (added class when active)
	 */
	$.fn.colExpander = function (options) {
		var $that = $(this);
		options = $.extend({
			show: false,
			fx: 'toggle',
			event: { hover: 'click', blur: 'mouseleave' },
			timeout: 250,
			triggerClass: '.trigger',
			containerClass: '.content',
			activeClass: 'active'
		}, options);

		// if clickable
		(options.show) ? $that.data('collapsed', false) : $that.data('collapsed', true);

		// initial setup
		($that.data('collapsed')) ? collapse(): expand();

		// expand container
		function expand(e) {
			if(e) e.preventDefault();
			if(options.fx == 'toggle') $that.find(options.containerClass).show();
			if(options.fx == 'slide') $that.find(options.containerClass).slideDown();
			if(options.fx == 'fade') $that.find(options.containerClass).fadeIn();
			// add active state
			$that.addClass(options.activeClass);
			// set new state
			setTimeout(function () {
				$that.data('collapsed', false)
			}, options.timeout);
		}

		// collapse container
		function collapse(e) {
			if(e && e.type == options.event.blur) {
				this.timer = setTimeout(function () {
					if(options.fx == 'toggle') $that.find(options.containerClass).hide();
					if(options.fx == 'slide') $that.find(options.containerClass).slideUp();
					if(options.fx == 'fade') $that.find(options.containerClass).fadeOut();
					// add active state
					$that.removeClass(options.activeClass);
					// set new state
					$that.data('collapsed', true)
				}, options.timeout);
			} else { clearTimeout(this.timer); }
		}

		// add hover event
		$that.find(options.triggerClass).bind(options.event.hover, function (e) {
			if($that.data('collapsed')) expand(e);
		});

		// add blur event
		$that.bind(options.event.blur, function (e) {
			if(!$that.data('collapsed')) collapse(e);
		});
		
		// default return value
		return this;
	};
	//$(item).colExpander({ triggerClass: '.trigger', containerClass: '.container' });

	/**
	 * iFrame Generator
	 * @version: 0.0.2
	 * @param: width (width of the iframe)
	 * @param: height (height of the iframe)
	 * @param: style (css that will be applied to the iframe)
	 * @param: src (taking either the link within the inner of the element or pass through src option)
	 */
	$.fn.iframe = function (options) {
		options = $.extend({ width: '100%', height: '100%', style: 'border:none; overflow:auto;'}, options);
		options.src = options.src || this.text();

		return this.each(function (e) {
			var iframe = '<iframe src="' + options.src + '" width="' + options.width + '" height="' + options.height + '" scrolling="no" frameborder="0" allowTransparency="true" style="' + options.style + '"></iframe>';
			$(this).html(iframe);
		});
	};
});
