/* Shop Manager */

var TsaiShop = function ( model ) {
	var manager = this,
		targets = null,
		thumbs = null,
		large = null,
		currentIndex = 0;

	this.controller = null,
	this.valUp = null,
	this.valDown = null,
	this.inputField = null,
	this.quantity = 0;

	var manageGallery = function ( e ) {
		e.preventDefault();

		var currentThumb = $(this);
		currentThumb.parent('li').addClass('active').siblings().removeClass('active');

		var img = new Image();
		img.src = currentThumb.attr('href').replace(/_microthumb/,'_image');
		$(img).css('opacity', 0);
		large.append( img );
		$(img).animate({
			opacity: 1
		});
		$(img).prev('img').animate({
			opacity: $.browser.msie !== true ? 0 : 1
		}, function () {
			$(this).remove();
		});
		large.css('height', large.children('img').height() );
	}

	this.gallery = function ( thumbnails, largeView ) {
		thumbs = thumbnails;
		large = largeView;
		large.css('height', large.children('img').height() );
		thumbs.eq(0).parent('li').addClass('active');
		thumbnails.unbind().bind('click', manageGallery);

	}

	this.reset = function () {
		manager.targets.not('.trans').stop().animate({
			opacity: 1
		}).find('.item-thumb-description').stop().animate({
			opacity: !$.browser.msie ? 0 : 1
		}).parent().siblings('.trans').stop().animate({
			opacity: !$.browser.msie ? .3 : 1
		}).find('.item-thumb-description').stop().animate({
			opacity: !$.browser.msie ? 0 : 1
		});
	}

	var moveToTop = function ( e ) {
		$('body').stop().animate({
			scrollTop: 0
		}, 750);
	}

	var Target = function ( key, obj ) {
		var target = this;
		var $el = $(obj).css('cursor', 'pointer');
		var $description = $el.find('.item-thumb-description').css('opacity', 0);
		$el.bind( 'mouseenter', manager.focus );
		$el.bind( 'click', moveToTop );
	}

	this.bind = function ( targets ) {

		if( targets.find('.active') ) {
			targets.find('.active').siblings().css('opacity', .3).addClass('trans');
		}

		manager.targets = targets.children();
		$.each( manager.targets, Target );
		targets.bind( 'mouseleave', manager.reset );
	}

	this.focus = function  ( e ) {
		$el = $(this);
		$el.stop().find('.item-thumb-description').andSelf().animate({
			opacity: 1
		});
		$el.siblings().not('.active').stop().animate({
			opacity: .3
		}).find('.item-thumb-description').stop().animate({
			opacity: $.browser.msie !== true ? 0 : 1
		});
	}

	var increaseQuantity = function () {
		manager.quantity = manager.quantity + 1;
		validateQuantity();
	}

	var decreaseQuantity = function () {
		manager.quantity = manager.quantity - 1;
		validateQuantity();
	}

	var validateQuantity = function () {
		if( manager.quantity < 0 ) {
			manager.quantity = 0;
		} else if ( manager.quantity > 99 ) {
			manager.quantity = 99;
		}
		updateQuantity();
	}

	var updateQuantity = function () {
		manager.inputField.val( manager.quantity );
	}

	var bindController = function () {
		manager.valUp.bind( 'click', increaseQuantity );
		manager.valDown.bind( 'click', decreaseQuantity );
		manager.inputField.bind( 'blur', validateQuantity );
	}

	this.quantify = function ( controller ) {;
		manager.controller = controller;
		manager.inputField = controller.prev('.shop-item-quantity');
		manager.valUp = controller.children('.quantity-controller-up');
		manager.valDown = controller.children('.quantity-controller-down');

		manager.quantity = parseInt( manager.inputField.val() );

		bindController();
	}

	var selectColor = function ( e ) {
		$color = $(this);
		$color.addClass('active').siblings().removeClass('active');
		$color.children('input').attr('checked', true);
	}

	this.colorSelector = function ( colors ) {
		colors.children('li').bind( 'click', selectColor );
		colors.children('li').eq(0).trigger('click');
	}

	var updateCart = function ( data ) {
		if( !data ) {
			$('.nav-cart').css('opacity', parseInt( $('.totalCart').text() ) > 0 ? 1 : .65 );
			return false;
		}

		var qty = 0;
		$.each( data, function ( key, item ) {
			if( data[key].qty ) qty += data[key].qty;
		} );
		$('.totalCart').text( qty );
		$('.nav-cart').css('opacity', qty > 0 ? 1: .65 );
		if( data.swap && data.html ) {
			$('.body').find('.kidObject').html( data.html.body );
			model.bindLinks();
		} else {
			window.location.href = '#/'+data['app-prefix']+'/'+data['shop-id']+'/shopping_cart/';
		}
	}

	var hijackCart = function ( e ) {
		e.preventDefault();
		$.ajax({
			type: 'POST',
			dataType: 'json',
			cache: false,
			data: {
				id: $('#shop-item-id').val(),
				color: $('input[name="color"]:checked').val(),
				qty: $('.shop-item-quantity').val(),
				func: 'addItems'
			},
			url: 'sites/tsai/tsai_ajax_post.php?p=tsai',
			timeout: 10000,
			success: updateCart,
			error: function ( XMLHttpRequest, textStatus, errorThrown ) {
				//document.location.href = targetHref;
			}
		});

	}

	var updateQtys = function( e ) {
		e.preventDefault();
		$.ajax({
			type: 'POST',
			dataType: 'json',
			cache: false,
			data: {
				func: 'adjustItems',
				data: $('.tsai-cart').serialize()
			},
			url: 'sites/tsai/tsai_ajax_post.php?p=tsai',
			timeout: 10000,
			success: updateCart,
			error: function ( XMLHttpRequest, textStatus, errorThrown ) {
				//document.location.href = targetHref;
			}
		});
	}

	this.addToCart = function ( btn ) {
		btn.bind( 'click', hijackCart );
	}

	this.updateCart = function ( btn ) {
		btn.unbind().bind( 'click', updateQtys );
	}

	var removeItem = function ( e ) {
		$(this).prev('input').val('0');
		$.ajax({
			type: 'POST',
			dataType: 'json',
			cache: false,
			data: {
				func: 'adjustItems',
				data: $('.tsai-cart').serialize()
			},
			url: 'sites/tsai/tsai_ajax_post.php?p=tsai',
			timeout: 10000,
			success: updateCart,
			error: function ( XMLHttpRequest, textStatus, errorThrown ) {
				//document.location.href = targetHref;
			}
		});
	};

	this.bindRemoves = function ( btns ) {
		btns.unbind().bind('click', removeItem );
	}

	updateCart();
}

/* Vimeo Player */
var TsaiVimeo = function () {
	var vimeo = this,
		flashvars = {
			clip_id: -1,
			show_portrait: 0,
			show_byline: 0,
			show_title: 0,
			js_api: 0,
			js_swf_id: 'moogaloop'
		},
		params = {
			allowscriptaccess: 'always',
			allowfullscreen: 'true'
		},
		attributes = {};

	var insertVimeo = function () {
		var target = $(this),
			id = target.attr('class').replace(/vimeo-holder vid-/,''),
			holder = target.attr('id');

		flashvars.clip_id = id;
		var vw = target.width(),
			vh = target.height();
		swfobject.embedSWF("http://vimeo.com/moogaloop.swf", holder, vw, vh, "9.0.0", "expressInstall.swf", flashvars, params, attributes);
	};

	this.check = function () {
		if( $('.vimeo-holder').length>0 ) {
			$('.vimeo-holder').each(insertVimeo)
		}
	}
}

/* Theme Manager */
var TsaiManager = function ( templates, eventManager, iTpl, vimeo ) {
	var manager = this,
		sidebar = null,
		submenu = null,
		body = null,
		quote = null,
		rightBorder = null,
		sections = [],
		tpl = templates,
		events = eventManager,
		currentTpl = templates[ iTpl ],
		theight = 0,
		shop = new TsaiShop( this ),
		columns = [],
		targetHref = null,
		$container = $('.container'),
		containerID = $container.attr('id'),
		containerTimer = null,
		masterObject = {},
		$email = null;

	this.CHANGE_STATE = "changeState";
	this.CHANGE_HEIGHT = "changeHeight";
	this.UPDATE_DATA = "updateData";

	this.ANIM_TIMER = 750;
	this.ANIM_EASING = null;

	this.setup = function( columns ) {

			columns[0].css('height', theight);
			columns[1].css('height', theight);
			columns[2].css('height', theight);
			columns[4].css('height', theight);

			/* Establish sections and instantiate their managers */
			manager.sidebar = new TsaiColumn( columns[0], events, manager, "clear_left", null );
			manager.submenu = new TsaiColumn( columns[1], events, manager, "submenu", null );
			manager.body = new TsaiColumn( columns[2], events, manager, "body", vimeo );
			manager.rightBorder = new TsaiColumn( columns[4], events, manager, "rightBorder", null );
			manager.quote = new TsaiQuoteManager( columns[3], events, manager, "quote", null );

			sections.push( manager.submenu, manager.body, manager.quote );

			manager.bindLinks();

			var args = [ currentTpl, true, {} ];
			events.dispatchEvent( manager.CHANGE_STATE, args );

			if( $('input[name="email"]').length > 0 ) bindEmailForm( $('input[name="email"]' ) );
	}

	this.getHeight = function () {
		return theight;
	}

	var bindEmailForm = function ( email ) {
		$email = email;
		$email.bind({
			focus: function ( e ) {
				if( $email.val().toLowerCase() == 'email' ) {
					$email.val('');
				}
			},
			blur: function  ( e ) {
				if( $email.val() == '' ) {
					$email.val('Email');
				}
			}
		});
		var submit = email.next('input');
		submit.bind('click', submitEmail);
	}

	var submitEmail = function ( e ) {
		e.preventDefault();

		$.ajax({
			type: 'POST',
			dataTyle: 'json',
			cache: false,
			data: {
				func: 'addEmail',
				email: $email.val()
			},
			url: 'sites/tsai/tsai_ajax_post.php?p=tsai',
			timeout: 10000,
			success: emailSent,
			error: function ( XMLHttpRequest, textStatus, errorThrown ) {
				//document.location.href = targetHref;
			}
		});

	}

	var emailSent = function ( data ) {
		$email.val( data.message );
	}

	var checkHeights = function () {
		var maxHeight = 0;
		var s;
		for( s = 0; s < sections.length; s++ ) {
			if( sections[s].hasOwnProperty('getHeight') ) {
				var height = sections[s].getHeight();
				maxHeight = height > maxHeight ? height : maxHeight;
			}
		}
		return maxHeight;
	}

	this.setHeight = function ( e ) {
		var cheight = checkHeights(),
			dheight = $(document).height(),
			nheight = cheight < dheight ? cheight : dheight,
			wheight = $(window).height();

		theight = nheight > wheight ? nheight : wheight;

		events.dispatchEvent( manager.CHANGE_HEIGHT );
	}

	this.bindLinks = function () {

		$('a').unbind( 'click', hijackLinks ).bind({
			click: hijackLinks
		});

		shop.bind( $('.sub-items') );

		if( $('.quantity-controller').length > 0 ) shop.quantify( $('.quantity-controller') );
		if( $('.shop-colors').length > 0  ) shop.colorSelector( $('.shop-colors') );
		if( $('.shop-image-thumb-button').length > 0 ) shop.gallery ( $('.shop-image-thumb-button'), $('.shop-image-large') );
		if( $('input.shop-add-to-cart').length > 0 ) shop.addToCart( $('input.shop-add-to-cart') );
		if( $('.update-cart').length > 0 ) shop.updateCart( $('.update-cart') );
		if( $('.remove').length > 0 ) shop.bindRemoves( $('.remove') );
	}

	var hijackLinks = function ( e ) {
		if( $(this).attr('target').toLowerCase() != '_blank' ) {
			e.preventDefault();

			if( $(this).hasClass('sub-toggle') ) {
				$(this).next('.nav-sub').slideToggle();
			}

			var target = e.currentTarget.href,
				targetParsed = parseURL( target ),
				id = targetParsed.params.id || 0,
				p = targetParsed.params.p || 0,
				template = $(this).attr('id');

			if( id == 0 || p == 0 || template == null ) {
				document.location.href = target;
			} else {
				targetHref = target;
				document.location.href = '#/'+p+'/'+id+'/'+template
			}
		}
	}

	var setPageData = function ( data ) {
		document.title = data.title;


		setTimeout( function () {
			manager.setHeight();
		}, 20)
	}

	var updateData = function ( data ) {
		$('.body').load( manager.setHeight );
		$('.sidebar').find('a').removeClass('active');
		$('.sidebar').find('a[class$="'+data.sidebarElement+'"]').addClass('active');

		if( !masterObject[ data.template ] ) {
			masterObject[ data.template ] = {};
		}

		if( !masterObject[ data.template ][ 'obj' + data.id ] ) {
			masterObject[ data.template ][ 'obj' + data.id ] = data;
			events.dispatchEvent( manager.UPDATE_DATA, [ data ] );
			setTimeout( function () {
				setPageData( data );
			}, manager.ANIM_TIMER + 10 );
		} else {
			setTimeout( function () {
				events.dispatchEvent( manager.UPDATE_DATA, [ data ] );
				setPageData( data );
			}, manager.ANIM_TIMER + 10 );
		}

	}

	var setTemplate = function ( template ) {
		var newTpl = tpl[ template ];
		var skip = false;

		if( newTpl == manager.currentTpl && newTpl == tpl['project'] ) {
			manager.ANIM_TIMER = 0;
			skip = true;
		} else {
			manager.ANIM_TIMER = 750;
			skip = false;
		}

		manager.currentTpl = newTpl;
		events.dispatchEvent( manager.CHANGE_STATE, [ newTpl, skip ] )

		$('body').stop().animate({
			scrollTop: 0
		}, 150 );
	}

	SWFAddress.onChange = function () {
		var path = SWFAddress.getPath(),
			pathArr = path.split('/'),
			_p = pathArr[1],
			_id = pathArr[2],
			_tpl = pathArr[3];

		containerID = _tpl;
		$container.attr( 'id', containerID );
		setTemplate( _tpl );

		if( pathArr.length > 2 ) {
			if( masterObject[_tpl] && masterObject[_tpl]['obj'+_id] && _tpl != 'shopping_cart' ) {
				updateData( masterObject[_tpl]['obj'+_id] );
			} else {
				$.ajax({
						type: 'GET',
						dataType: 'json',
						cache: false,
						url: 'sites/tsai/tsai_ajax_interface.php?p=' + _p + '&id=' + _id + '&tpl=' + _tpl,
						timeout: 10000,
						success: updateData,
						error: function ( XMLHttpRequest, textStatus, errorThrown ) {
							document.location.href = targetHref;
						}
				});
			}
		}
	}

	$(window).bind('resize', manager.setHeight );
	$(window).load( manager.setHeight );
}

/* Column manager */

var TsaiColumn = function ( domElement, eventManager, manager, str, vimeo ) {
	var column = this,
		$el = domElement,
		events = eventManager,
		controller = manager,
		tplString = str,
		currentTpl = null,
		oldTpl = null,
		currentData = null,
		$kidObject = $el.wrapInner('<div class="kidObject clearfix"/>').children('.kidObject'),
		locked = false;

	var cb = function () {
		$kidObject.width = $el.width();
	}

	var updateData = function ( props ) {
		var data = props[0],
			currentData = data[tplString];
		if( currentData ) {
			$kidObject.css('display','inline-block');
			$kidObject.html( currentData ).stop().animate({
				opacity: 1
			}, function() {
				$(window).trigger('resize');
			});
			controller.bindLinks();

			if( vimeo ) {
				vimeo.check();
			}
		}
		else {
			$kidObject.html('').css('display','none');
		}
	}

	var changeState = function ( props ) {
		currentTpl = props[0] ? ( props[0][tplString] || null ) : null;

		if( currentTpl != null ) {
			var skip = props[1] || null,
				animObj = {
					width: currentTpl.width || null,
					paddingLeft: currentTpl.padding || 0,
					paddingRight: currentTpl.padding || 0,
					borderRightWidth: currentTpl['border-right-width'] || 0,
					borderLeftWidth: currentTpl['border-left-width'] || 0
				}

			if( !skip ) {
				$kidObject.stop().animate({
					opacity: !$.browser.msie ? 0 : 1
				}, controller.ANIM_TIMER, function(){
					$kidObject.children().remove();
				});
			}

			$el['stop']()[ ( skip ? 'css' : 'animate' )  ]( animObj, controller.ANIM_TIMER, controller.ANIM_EASING, cb );
		}

	}

	var updateHeight = function () {
		$el.css({
			height: controller.getHeight()
		});
	}

	this.getHeight = function () {
		return $el.find('.kidObject').height() + 40;
	}

	events.addListener( new Event( controller.CHANGE_HEIGHT, updateHeight ) );
	events.addListener( new Event( controller.CHANGE_STATE, changeState ) );
	events.addListener( new Event( controller.UPDATE_DATA, updateData ) );
}

var TsaiQuoteManager = function ( domElement, eventManager, manager, str ) {
	var quote = this,
		$el = domElement,
		events = eventManager,
		controller = manager,
		tplString = str;

	var updateQuote = function ( props ) {
		var skip = props[1] || null,
			quote = props[0].quote;

		if( !skip && quote != null ) {
			$el.html( quote ).animate({
				opacity: 1
			});
		} else if( !skip ) {
			$el.animate({
				opacity: $.browser.msie != true ? 0 : 1
			}, function(){
				$el.html('');
			});
		}

	}

	events.addListener( new Event (controller.UPDATE_DATA, updateQuote) );

}

/* Event Manager */
var Event = function ( e, cb, data ) {

	if( !e || !cb )
		return "Improper event request";

	this.e = e;
	this.cb = cb;
	this.data = data || null;
};

var EventManager = function () {
	var events = new Array();

	this.addListener = function ( evt ) {
		var len = events.length;
		var eventExists = false;
		if( len > 0 ) {
			var i;
			for( i = 0; i < len; i++ ) {
				if( events[i].e == evt.e && events[i].cb == evt.cb )
					eventExists = true;
			};
			if( !eventExists ) events.push(evt);
		} else {
			events.push( evt );
		}
	};

	this.removeListener = function ( evt ) {
		var len = events.length;
		var i;
		for( i = 0; i < len; i++ ) {
			if( events[i].e == evt.e && events[i].cb == evt.cb ) events.splice(i,1);
		};
	};

	this.dispatchEvent = function ( evt, data ) {
		var len = events.length;
		var i;
		for( i = 0; i < len; i++ ) {
			if( events[i].e == evt) {
				events[i].cb( data );
			}
		};
	};

	this.eventList = function () {
		return events;
	};
};

/* URL Parser */

function parseURL(url) {
    var a =  document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':',''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function(){
            var ret = {},
                seg = a.search.replace(/^\?/,'').split('&'),
                len = seg.length, i = 0, s;
            for (;i<len;i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
        hash: a.hash.replace('#',''),
        path: a.pathname.replace(/^([^\/])/,'/$1'),
        relative: (a.href.match(/tp:\/\/[^\/]+(.+)/) || [,''])[1],
        segments: a.pathname.replace(/^\//,'').split('/')
    };
}

/* jQuery initalize code when DOM is ready */
jQuery(window).bind("unload", jQuery.noop);

$(function(){

	$('body').css('display', 'none');
	setTimeout( function () {
		$(window).trigger('resize');
	}, 5 );
	$(window).bind('load', function(){
		$('body').css('display', 'inline-block');

		$(window).unbind('load').trigger('resize').bind({
			load: function ( e ) {
				$(window).trigger('resize');
			}
		});
	});


	function establish( data ) {
		if( !$.browser.msie ) {
			$('.fade').css('opacity', .6 );
		}
		$('.nav-sub').hide();

		var eventManager = new EventManager(),
			vimeo = new TsaiVimeo(),
			iTpl = $('.container').attr('id'),
			manager = new TsaiManager( data, eventManager, iTpl, vimeo ),
			columns = [];

		$submenu = $('.sub-menu');
		$body = $('.body');
		$quote = $('.quote');
		$sidebar = $('.clear_left');
		$rightBorder = $('.clear_right');
		columns.push( $sidebar, $submenu, $body, $quote, $rightBorder );
		manager.setup( columns );
		vimeo.check();
	}

	$.getJSON('sites/tsai/templates/templates.json', establish);

});
