/**
 * @section   : Global JavaScript functions
 * @project   : Dr. Sticker / Online Sticker
 * @author    : Joris van Summeren <joris@e-sites.nl>
 * @version   : 1.0
 */

// Global variables
var addthis_config;

/* Prototyping for currency functions */
String.prototype.reverse = function () {
	return this.split("").reverse().join("");
};

String.prototype.toFloat = function () {
	return parseFloat( this.replace(',', '.').replace('€', '') );
};

Number.prototype.withCommas = function () {
	var x = 6,
		y = parseFloat(this).toFixed(2).toString().reverse();
	while (x < y.length) {
		y = y.substring(0, x) + "," + y.substring(x);
		x += 4;
	}

	return y.reverse().replace(/,/g, ':').replace(/\./g, ',').replace(/:/g, '.');
};

Number.prototype.toCurrency = function () {
	return (arguments[0] ? arguments[0] : "€ ") + this.withCommas();
};

/**
 * Init unobtrusive jQuery tab functionality, fades in corresponing clicked tab and equalizes all tabs
 *
 * @return this - jQuery Object
 * @author Joris van Summeren <joris@e-sites.nl>
 * @since 2 feb 2010
 */
jQuery.fn.tabs = function () {
	return this.each(function () {

		var self = $(this),
			tabs = self.find('.tab'),
			tabIdx = jQuery('#tabIdx ol');

		tabs.not('.top').children('.inner').hide();

		jQuery('#tabIdx a').bind('click', function (e) {
			var link = $(this),
				index = $('#tabIdx a').index(link);

			jQuery('#tabIdx .active').removeClass('active');
			jQuery('#tabIdx li').eq(index).addClass('active');

			tabs.children('.inner').fadeOut('fast').end().removeClass('top');
			tabs.eq(index).addClass('top').children('.inner').fadeIn();

			link.blur();
			e.preventDefault();
		});

		jQuery('.tab').equalizeCols();

	});
};

/* Opens clicked link in new tab/window */
function setExtLinks() {
	this.target = '_blank';
}

/**
 * Tiny plugin which shows extra form fields based on a selectbox value. Current value from the selectbox
 * is evaluated to see if the related wrapper should be visible. (Usually when a form is posted and
 * there are php errors).
 *
 * @param none
 * @return this - jQuery Object
 * @usage Wrap the extra form fields in a div with id [selectID] + Wrapper
 * @example div#emailWrapper will be toggled when changing select#email
 * @author Joris van Summeren <joris@e-sites.nl>
 * @since 20 jan 2010
 */
jQuery.fn.togglePaymentFields = function () {
	return this.each(function () {
		var self = $(this),
			extraFields = $('#' + self.attr('id') + 'Wrapper');

		self.bind('change', function() {
			if (self.val() === 'Automatische incasso' || self.val() === 'Vooruitbetalen') {
				extraFields.show();
			}
			else {
				extraFields.hide();
			}
		}).change();
	});
};

/**
 * Tiny plugin which shows extra form fields based on a checkbox value. Current value from the checkbox
 * is checked to see if the related wrapper should be visible. (Usually when a form is posted and
 * there are php errors).
 *
 * @param none
 * @return this - jQuery Object
 * @usage Wrap the extra form fields in a div with id [inputID] + Wrapper
 * @example div#emailWrapper will be toggled when clicking input#email
 * @author Joris van Summeren <joris@e-sites.nl>
 * @since 20 jan 2010
 */
jQuery.fn.toggleExtraFields = function () {
	return this.each(function () {
		var input = $(this),
			extraFields = $('.' + input.attr('id') + 'Wrapper');

		input.bind('click', function () {
			extraFields.toggle();
		});

		if ( input.is(':checked') ) {
			extraFields.show();
		} else {
			extraFields.hide();
		}
	});
};

/**
 * Changes hidden select based on the clicked li. The id from the li should correspond with the select value.
 *
 * @param none
 * @return void
 * @author Joris van Summeren <joris@e-sites.nl>
 * @since 3 feb 2010
 */
function initShippingOptions() {
	var list = $('#optionList');

	$('#shippingOptions').hover(function () {
		list.show();
	}, function() {
		list.hide();
	});

	$('#optionList li').bind('click', function (e) {
		var self = $(this),
			id = self.attr('id'),
			price = self.attr('class').toFloat().toCurrency();

		$('#shippingSelect').val(id);
		$('#current').html(self.html());
		list.hide();
		$('#pr-ship').text(price);
		togglePhoneContact();
	});
}

/**
 * Update complete costs table in shopping cart with ajax
 *
 * @param e - jQuery Object
 * @return void
 * @author Joris van Summeren <joris@e-sites.nl>
 * @since 5 feb 2010
 */
function updateCosts(e) {
	var self = $(e.target),
		row = self.closest('tr'),
		rows = row.parent().children('tr'),
		lastCell = row.find('td:last'),
		formData = $('#orderOverviewFrm').serialize(),
		hasDiscount = false,
		rowPrice,
		discountCode = $('#discountCode'),
		discountCodeLbl = discountCode.next(),
		subtotal = $('#pr-sub'),
		totalDiscount = $('#pr-discount'),
		subtotalAfterDiscount = $('#pr-subtotalAfterDiscount'),
		discountSet = $('#pr-discountountLbl, #pr-subtotalAfterDiscountLbl').add(totalDiscount).add(subtotalAfterDiscount);

	lastCell.addClass('loading');

	$.ajax({
		type: 'POST',
		url: '/php/updatemandje.php',
		data: formData,
		success: function (response) {
			if (typeof response === 'object') {
				var regels = response.regels;

				if (regels !== []) {
					for (var i = 0, j = regels.length; i < j; i++) {
						var info = regels[i],
							currRow = rows.eq(i + 1);

						if (info.regelDiscount === true) {
							hasDiscount = true;
							rowPrice = '<del>' + info.regelPrijsNoDiscount + '</del><br><span class="afterDiscount">Na korting</span>' + info.regelPrijs;
						} else {
							rowPrice = info.regelPrijs;
						}

						currRow.find('td:eq(2)').text(info.eenheidsPrijs);
						currRow.find('td:eq(3)').children('input').val(info.aantal);
						currRow.find('td:eq(4)').html(rowPrice);
					}
				}

				/* Show the user if his discount code is valid */
				if ($.trim(discountCode.val()) === '') {
					discountCodeLbl.html('');
				} else {
					if (hasDiscount) {
						discountCodeLbl.html('<span style="color:green;">Goed!</span>');
					} else {
						discountCodeLbl.html('<span style="color:red;">Fout!</span>');
					}
				}

				if (hasDiscount) {
					subtotal.text(response.subtotaalNoDiscount);
					totalDiscount.html(response.totalDiscount + '<br>');
					subtotalAfterDiscount.html(response.subtotaal + '<br>');
					discountSet.show();
					subtotalAfterDiscount.css('display', 'block');
				} else {
					discountSet.hide();
					subtotal.text(response.subtotaal);
				}

				$('#pr-ship').text(response.verzendkosten);
				$('#pr-btw').text(response.btw);
				$('#pr-total').text(response.totaal);

				remboursCheck(response.subtotaal, response.btw);
			}

			lastCell.removeClass('loading');
		},
		dataType: 'json'
	});
}

/**
 * Shows additional notes when customer selects 'spoed afhalen' or 'spoed koerier'
 *
 * @param none
 * @return void
 * @author Joris van Summeren <joris@e-sites.nl>
 * @since 5 feb 2010
 */
function togglePhoneContact() {
	var shippingType = $('#shippingSelect').val(),
		phoneContact = $('#phoneContact');

	if (shippingType === 'option5' || shippingType === 'option6') {
		phoneContact.fadeIn();
	} else {
		phoneContact.fadeOut();
	}
}

/**
 * Adjust different shape options based on the chosen fabric at offerpage
 *
 * @param e - jQuery Object
 * @return void
 * @author Joris van Summeren <joris@e-sites.nl>
 * @since 8 feb 2010
 */
function adjustShapes(e) {
	var self = $(e.target),
		val = self.val().toLowerCase(),
		shapeWrapper = $('#shapeWrapper'),
		finishWrapper = $('#finishWrapper'),
		finishBannerWrapper = $('#finishBannerWrapper');

	shapeWrapper.show();
	finishWrapper.hide();

	switch (val) {
		case 'full colour':
			fillShapeSelect('Vierkant', 'Rechthoek', 'Rond', 'Ovaal', 'Contour');
			finishBannerWrapper.hide();
			finishWrapper.show();
			break;
		case 'plakletter':
		case 'snijvinyl':
			finishBannerWrapper.hide();
			shapeWrapper.hide();
			break;
		case 'canvas':
			finishBannerWrapper.hide();
			fillShapeSelect('Staand', 'Liggend');
			break;
		case 'spandoek':
			shapeWrapper.hide();
			finishWrapper.hide();
			finishBannerWrapper.show();
			break;
		default:
			fillShapeSelect('Kies eerst de materiaalsoort');
	}
}

/**
 * Fill's shape select with new options, based on the chosen fabric at offerpage
 *
 * @param none
 * @return void
 * @author Joris van Summeren <joris@e-sites.nl>
 * @since 8 feb 2010
 */
function fillShapeSelect() {
	var j = arguments.length,
		options = '<option value="">Maak een keuze</option>';

	if (j) {
		for (var i = 0; i < j; i++) {
			options += '<option value="' + arguments[i] + '">' + arguments[i] + '</option>';
		}
	}

	$('#shape').html(options);
}

/**
 * Toggle's the option to order with rembours. You can only order with rembours if the subtotal price is over 50 euro's
 *
 * @param subtotal - String
 * @param btw - String (we don't use this anymore) BTW is already included in subtotal
 * @return void
 * @author Joris van Summeren <joris@e-sites.nl>
 * @since 26 feb 2010
 */
function remboursCheck(subtotal, btw) {
	var subtotal = subtotal.split('.').join('').split(',').join('.').toFloat(),
		total = subtotal,
		remboursOption = $('#optionList #option2');

	if (total < 50) {
		remboursOption.hide();
	} else {
		remboursOption.show();
	}
}

/**
 * Only show extra business related input fields if necessary
 *
 * @param
 * @return void
 * @author Joris van Summeren <joris@e-sites.nl>
 * @since 5 mrt 2010
 */
function toggleBusinessFields() {
	var self = $(this),
		id = self.attr('id'),
		wrapper = $('.businessWrapper');

	if (id === 'business') {
		wrapper.show();
	} else {
		wrapper.hide();
	}
}

/**
 * This function reloads a page
 *
 * @param none
 * @return void
 * @author Bas van Kuijck <bas@e-sites.nl>
 * @since 20 apr 2010
 */
function reloadPage() {
	if (confirm('Zeker weten dat je opnieuw wilt beginnen?')) {
		location = window.location;
	}
}

/**
 * This function resizes or shrinks the sticker design tool
 *
 * @param resize Boolean true = resize, false = shrink
 * @return void
 * @author Bas van Kuijck <bas@e-sites.nl>
 * @since 27 apr 2010
 */
function resizeElement(resize) {
	var w = (resize?975:642),
		f = 642 / 720,
		h = w / f;

	$("#wizardFlashElement").css({width: w + 'px', height: h + 'px' });
	$("#wizardFlashPlaceHolder").css({height: h + 'px' });
}

/**
 * Function to open the facebook share popup
 */
function faceBookSharer(domain) {
	var u = 'http://www.drsticker.nl?fb',
		t = 'Dr. Sticker - Online stickers bestellen!';
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
}

/**
 * Loads and initializes AddThis functionality after DOMContentLoaded
 *
 * @param none
 * @return void
 * @author Joris van Summeren <joris@e-sites.nl>
 * @since 3 dec 2010
 */
function initAsyncAddthis() {
	var self = this,
		username = 'drsticker',
		gaProfile = 'UA-3990588-1',
		times = 40;

	addthis_config = {
		username: username,
		services_compact: 'email,facebook,twitter,hyves,print,favorites,blogger,google,delicious,netvibes,hotmail,gmail,bitly,more',
		data_ga_tracker: null,
		data_track_clickback: true,
		ui_language: 'en'
	};

	_gaq.push(function () {
		addthis_config.data_ga_tracker = _gat._getTracker(gaProfile);
	});

	this.init = function () {
		if (typeof addthis === 'object') {
			addthis.init();
		} else {
			if (!times) return;

			setTimeout(self.init, 25);
			times--;
		}
	}

	$.getScript('http://s7.addthis.com/js/250/addthis_widget.js#domready=1&async=1&username=' + username, self.init);
}


