/* JQuery Plugin: "EqualHeights" & "EqualWidths" via http://www.filamentgroup.com/lab/setting_equal_heights_with_jquery/ */
jQuery.fn.equalHeights=function(e){jQuery(this).each(function(){var t=0;jQuery(this).children().each(function(e){if(jQuery(this).height()>t){t=jQuery(this).height()}});if(!e||!Number.prototype.pxToEm)t=t.pxToEm();if(jQuery.browser.msie&&jQuery.browser.version==6){jQuery(this).children().css({height:t})}jQuery(this).children().css({"min-height":t})});return this};jQuery.fn.equalWidths=function(e){jQuery(this).each(function(){var t=0;jQuery(this).children().each(function(e){if(jQuery(this).width()>t){t=jQuery(this).width()}});if(!e||!Number.prototype.pxToEm)t=t.pxToEm();if(jQuery.browser.msie&&jQuery.browser.version==6){jQuery(this).children().css({width:t})}jQuery(this).children().css({"min-width":t})});return this};Number.prototype.pxToEm=String.prototype.pxToEm=function(e){e=jQuery.extend({scope:"body",reverse:false},e);var t=this==""?0:parseFloat(this);var n;var r=function(){var e=document.documentElement;return self.innerWidth||e&&e.clientWidth||document.body.clientWidth};if(e.scope=="body"&&jQuery.browser.msie&&(parseFloat(jQuery("body").css("font-size"))/r()).toFixed(1)>0){var i=function(){return(parseFloat(jQuery("body").css("font-size"))/r()).toFixed(3)*16};n=i()}else{n=parseFloat(jQuery(e.scope).css("font-size"))}var s=e.reverse==true?(t*n).toFixed(2)+"px":(t/n).toFixed(2)+"em";return s}

jQuery(function($) {

	$( 'div[data-model-type]' ).each(function(index,elem){
		var id = 'staticblock' + index;
		$(elem).attr('contenteditable','true').css('display','inline').attr('id', id);
		CKEDITOR.inline( id );
	});


	if( $.browser.msie && parseFloat( $.browser.version ) >= 10 )
	{
		$( 'html' ).addClass( 'is-ie' ).addClass( 'is-ie10' );
	}

	$( '.swm-colorbox' ).colorbox({
		iframe: true,
		width: '80%',
		height: '80%',
		overlayClose: false,
		escKey: false,
		fixed: true
	});

	$( '.swm-colorbox-inline' ).colorbox({
		height: '80%',
		overlayClose: true,
		escKey: true,
		fixed: true
	});

	$( '.colorbox-action-close' ).click(function() {
        window.parent.$.colorbox.close();
    });

	// If the user agent is Safari, handle the ability to click on labels to
	// set checkboxes.
	if (navigator.userAgent.indexOf("Safari") > 0)
	{
	    var labels = jQuery( 'label' );
	    for( i = 0; i < labels.length; i++ )
	    {
	        jQuery( labels[i] ).live( 'click', function() {
	            jQuery( 'input[type=checkbox] #' + this.getAttribute( 'for' ) ).each( function() {
	                this.checked = ! this.checked;
	            })
	        });
	    }
	}

	// See if there's any fields that need to have the validation-failed class
	// added to them.
	if( jQuery( 'input, select, textarea' ).length > 0 )
	{
		jQuery.post( '/api/status/invalidfields?format=json', function( response ) {
			var foundFields = [];

			for( var selector in response )
			{
				if( jQuery( selector ).length > 0 )
				{
					foundFields.push( selector );
					jQuery( selector ).addClass( 'validation-failed' );
				}
			}

			if( foundFields.length > 0 )
			{
				// Pop up the validation messages
				tb_show( 'Validation Errors', '/api/status/invalidfields?showonly=' + escape( foundFields.join( '|' ) ) + '&clearfields=true&width=450&height=250&TB_iframe=true&modal=true' );
			}
		});
	}

	// Apply the sfhover class to nested navigation list items
	// as per http://www.htmldog.com/articles/suckerfish/dropdowns/
	jQuery( '#nav.nav-nested li' ).bind({
		mouseover: function() {
			jQuery( this ).addClass( 'sfhover' );
		},
		mouseout: function() {
			jQuery( this ).removeClass( 'sfhover' );
		}
	});

	// find any iframes that look like they might be embedded youtube videos
	// and surround them with a div so we can style them properly
	// (disabled with class 'no-autocontainer')
	jQuery( 'iframe[src*="youtube.com"]:not(.no-autocontainer)' ).wrap( '<div class="youtube-container"></div>' );

	jQuery( '#item-list .product-summary .product-option-add-to-cart' ).click( function() {
		// Don't perform this action for links that have data-type="product-details"
		if( $(this).attr('data-type') == 'product-details' ) {
			return true;	// returning with true performs the usual action for the link
		}

		var link = this;
		jQuery(link).html('adding ...');
		jQuery('body').css('cursor', 'progress');
		$.ajax({
			type: 'get',
			url: this.getAttribute('href'),
			dataType: 'html',
			success: function(html) {
				jQuery(link).html( 'added' );
				jQuery('body').css( 'cursor', 'auto' );
				SWM.fire( 'store.cart.update' );
			}
		});
		return false;
	});

	jQuery( '#item-list > table .product-option-add-to-cart, .productdetails .product-option-add-to-cart' ).removeAttr( 'onclick' );
	jQuery( '#item-list > table .product-option-add-to-cart, .productdetails .product-option-add-to-cart' ).click( function() {
		var element = jQuery(this);
		jQuery('body').css('cursor', 'progress');

		var method;
		var url;
		if (element.is('input')) {
			var form = $(this.form);
			method = form.attr('method');
			url = form.attr('action') + '?' + form.serialize();
			element.attr('value', 'adding ...');
		} else {
			method = 'get';
			url = this.getAttribute('href');
			element.html('adding ...');
		}

		$.ajax({
			type: method,
			url: url,
			dataType: 'html',
			success: function(html) {
				var cart  = jQuery('.teaser.box.cart:visible').offset();
				if(cart !== undefined) {
					$('html, body').animate({scrollTop:cart.top-100}, 'slow', function() {
						var image = jQuery('.product-body img').get( 0 );
						if( image != undefined ) {
							image = jQuery(image);
							var imageSource = image.attr('src');
						} else {
							image = jQuery('h2.cat-list-item-title');
							var imageSource = '/theme/images/no-image.jpg';
						}

						jQuery(document.body).append(
							'<img src="' + imageSource + '" class="add-to-cart-temp-image" style="border: 1px rgba(0,0,0,0.25) solid; position: absolute; top: ' + image.offset().top + 'px; left: ' + image.offset().left + 'px;" />'
						);

						params = {
							top : cart.top + 'px',
							left : cart.left + 'px',
							opacity : 0.0,
							width : jQuery('.teaser.box.cart:visible:first').width(),
							height : jQuery('.teaser.box.cart:visible:first').height()
						};

						jQuery( '.add-to-cart-temp-image' ).animate( params, 'slow', false, function() {
							jQuery(this).remove();
						});
					});
				}
				if (element.is('input')) {
					element.attr('value', 'added');
				} else {
					element.html('added');
				}
				jQuery('body').css('cursor', 'auto');
				SWM.fire('store.cart.update');
			}
		});
		return false;
	});

	jQuery('textarea.allow-tabs').bind('keydown', function(event) {
		if (event.which == 9) {
			event.preventDefault();
			var start = this.selectionStart;
			var end = this.selectionEnd;
			this.value = this.value.substring(0, start) + '\t' + this.value.substring(end);
			this.selectionStart = start + 1;
			this.selectionEnd = start + 1;
		}
	});

	$(window).resize(function() {
		// Interchange any images:
		$('img[data-interchange]').each(function(i, img){
			var data = JSON.parse($(img).attr('data-interchange'));
			var w = $(window).width();
			var k;
			if (w<768) {
				k = 'small';
			} else if (w<1080) {
				k = 'medium';
			} else {
				k = 'large';
			}

			if(data[k] === undefined) {
				k = 'default';
			}

			if(data[k] !== undefined) {
				$(img).attr('src', data[k]);
			}
		});
	});
	// Trigger a resize so any interchanges get processed
	$(window).trigger('resize');

});

/**
* outerHTML
* Source: http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html
* Usage: jQuery( '#element' ).outerHTML
**/
(function($) {
  $.fn.outerHTML = function()
  {
    return $(this).clone().wrap('<div></div>').parent().html();
  }
})(jQuery);

function updateRegionControl( controlName, countryId )
{
	// Ask the server for a list
	jQuery.get(
		'/api/address/getRegionHtml',
		{
			controlName: controlName,
			countryId: countryId
		}, function( response ) {

			var container = jQuery( '#' + controlName ).get( 0 ).parentNode;
			jQuery( container ).html( response );
		}
	);
}


function disableLinks()
{
	var links = document.getElementsByTagName('A');
	for (var c=0; c<links.length; c++)
	{
		links[c].href='#';
		links[c].onclick = function() { window.setTimeout('alert(\'Links are disabled in preview mode.  Close this tab or window to return to the theme selection screen.\');',10); return false; }
	}
}

function validateEmail(elem,params)
{
	if (params.onCheck)	params.onCheck(elem);
	new Ajax.Request('/admin/rpc/action.php?asset=validate&action=email',
	{
		method: 'post',
		parameters: {
			input: elem.value
		},
		onSuccess: function(trans) {
			params.onSucecss(elem);
		},
		onFailure: function(trans) {
			params.onFailure(elem);
		}
	});
}

function showErrorMessage(message)
{
	window.setTimeout(function(){ alert(message); },50);
}

function ajaxMessage(message,timeout)
{
	jQuery( 'body' ).append( '<div class="ajax-message"><span>' + message + '</span></div>' );
	window.setTimeout( function() {
		jQuery( '.ajax-message' ).fadeOut(
			'fast',
			function(){
				jQuery( this ).remove();
			}
		)
	}, timeout );
}

// Method for email validation
// Checks the positions of @ and the last .
function validEmail( emailAddress ){

	// If the email address has a space in it, abort
	if( emailAddress.indexOf(' ') != -1 )
	{
		return false;
	}

	// A . and @ must be present and the last . must be no closer than 2 chars from the @
	// e.g. bob@a.com
	var atPos = emailAddress.indexOf( '@' );
	var dotPos = emailAddress.lastIndexOf( '.' );
	if( atPos == -1 || dotPos == -1 || ( atPos + 2 ) >= dotPos )
	{
		return false;
	}

	// Email address is valid
	return true;
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    } else var expires = "";
    document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = escape(name) + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length, c.length));
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}
// Full credit for this example goes to Stoyan Stefanov and his
// amazing book JavaScript Patterns
// http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752
// http://robdodson.me/blog/2012/08/16/javascript-design-patterns-observer/

"use strict";

SWM = {
	subscribers: {
		any: [] // event type: subscribers
	},
	on: function(type, fn, context) {
		type = type || 'any';
		fn = typeof fn === 'function' ? fn : context[fn];
		if (typeof this.subscribers[type] === "undefined") {
			this.subscribers[type] = [];
		}
		this.subscribers[type].push({ fn: fn, context: context || this });
	},
	remove: function(type, fn, context) {
		this.visitSubscribers('unsubscribe', type, fn, context);
	},
	fire: function(type, publication) {
		this.visitSubscribers('publish', type, publication);
	},
	visitSubscribers: function(action, type, arg, context) {
		var pubtype = type || 'any',
			subscribers = this.subscribers[pubtype],
			i,
			max = subscribers ? subscribers.length : 0;

		for (i = 0; i < max; i += 1) {
			if (action === 'publish') {
				// Call our observers, passing along arguments
				 subscribers[i].fn.call(subscribers[i].context, arg);
			} else {
				if (subscribers[i].fn === arg && subscribers[i].context === context) {
					subscribers.splice(i, 1);
				}
			}
		}
	},

	viewport: {
		isSmall: function() { return $('#viewport-detector-small').is(':visible'); },
		isMedium: function() { return $('#viewport-detector-medium').is(':visible'); },
		isLarge: function() { return $('#viewport-detector-large').is(':visible'); },
		state: function() { return {
			small: SWM.viewport.isSmall(),
			medium: SWM.viewport.isMedium(),
			large: SWM.viewport.isLarge(),
		} },
	},
};


SWM.on('store.cart.update', function() {
	jQuery.get('/pages/9', function(content) {
		var cartTeaser = jQuery('.teaser.box.cart:first', content).outerHTML();
		jQuery('.teaser.box.cart').replaceWith(cartTeaser);
	});
});
