/* Author: 
Isobar
*/

  // Handler for .ready() called.
	Cufon.replace('.stagBook', { fontFamily: 'Stag Book' });
	Cufon.replace('.interstateRegular', { fontFamily: 'Interstate-Regular' });
	Cufon.replace('.interstateBold', { fontFamily: 'Interstate-Bold' });


mattelJS = {
	common: {
		init: function() {						
			$(".langBtn").click(mattelJS.common.setLang);
			
			$("header #facebookLink").click(function(){
				var url = $('header').data('share-link');
				mattelJS.common.fbs_click(url);
			});
			
			$("header #twitterLink").click(function(){
				var url = $('header').data('share-link');
				var text = $('header').data('share-text');
				mattelJS.common.twitter_click(url,text);
			});
			
			$('header #emailLink').openDOMWindow({ 
				eventType:'click',
				width: 300,
				height: 200
			});
			
			$("#siteEmailShare #submitBtn").click(function(){
				var $this = $(this);
				
				
				if($("#siteEmailForm [type='text']").val()){
					
					$.post('/site/email/',{'to' : $("#siteEmailForm [type='text']").val()},function(data){
						if(data.success){
							alert($this.data('success-msg'));
						}
						$("#siteEmailForm [type='text']").val('');
						$.closeDOMWindow();
					});
				}
			});
			
			
			
			
		},
		setLang: function(){
			
			var data = { 'language':$(this).data('lang') };
			//console.log(data);
			
			if($(this).data('next') != null){
				data['next'] = $(this).data('next');
			}
			
       		$.postGo('/i18n/setlang/',data);
        	return false;
		},
		fbs_click: function(url) {
			var u=url;
			var t=document.title;
			window.open('http://www.facebook.com/sharer.php?u='+u+'&amp;t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;
		},
		twitter_click: function(url,text) {
			window.open('http://twitter.com/share?text='+encodeURIComponent(text)+'&url='+encodeURIComponent(url),'sharer','toolbar=0,status=0,width=626,height=436');return false;
		}
	},
	
	index: {
		init: function() {
		}
	},	
	
	user:{
		init: function() {
			
		},
		login: function() {
			$('#registration').load('/register/?next='+$("input:hidden[name=next]").val());
		},
		registration: function() {
			Cufon.refresh();
			
			var validator = $('#register_form').validate({
				debug:true,
				onsubmit: true,
				onfocusout: false,
				onkeyup: false,
				onclick: false,
		        rules: {
		            first_name: "required",
		            last_name: "required",
		            password1: {
		                required: true
		            },
		            password2: {
		                required: true,
		                equalTo: "#id_password1"
		            },
		            email: {
		                required: true,
		                email: true
		            }
		        },
		        showErrors: function(errorMap, errorList) {
		        	var summary = "";
		            $.each(errorList, function() {
		            	 summary += this.message + "\n"; 
		           	});
		           	if(errorList.length) alert(summary);
		            
		        },
		        
		        messages: {
		            first_name: gettext('Enter your first name'),
		            last_name: gettext('Enter your last name'),
		            password1: {
		                required:  gettext('Provide a password')
		            },
		            password2: {
		                required:  gettext('Repeat your password'),
		                equalTo:  gettext('Enter the same password as above')
		            },
		            email: {
		                required: gettext('Please enter an email address'),
		                minlength: gettext('Please enter a valid email address')
		            }
		        },
		        submitHandler: function(form) {
		        	var jqxhr = $.post($(form).attr('action'),$(form).serialize(), function(data) {
						$('#registration').html(data);
					})
					.complete(function() { 
						if (jqxhr.status == 278) {
				            window.location.href = jqxhr.getResponseHeader("Location");
				        }
				 	});
		        }
		    });
			
		}
	},
	
	gifts: {
		init: function(){
			$("a > #findToysBtn").click(function(){
				
				if($(".filter form :input[value='']").length){
					alert(gettext('All fields are required'));
				}else{
					$(".filter form").submit();
				}
				
				
			});
			
			
			$(".toy_image").tooltip({
				// each trashcan image works as a trigger
				tip: '#tooltip',
				onBeforeShow: function(event) {
					var trigger = this.getTrigger(), tip = this.getTip();
					tip.find('.description').html(trigger.data('description'));
					tip.find('.product-name').html(trigger.data('product-name'));
					tip.find('#bt_more_info').attr('href',trigger.data('product-link'));
				},
				
				effect: 'fade',
				// move tooltip a little bit to the right
				offset: [40, 0],
				// there is no delay when the mouse is moved away from the trigger
				delay: 0.5,
				predelay: 50
			});
			
			$('#bt_more_info').openDOMWindow({ 
				eventType:'click', 
				width : 650,
		        loader:0, 
		        windowSource:'ajax' 
			});
		},
		finder : function(){
			var $scroller = $('#wishlist_scroller');
			
			$("#right-arrow").click(function(){
				$scroller.animate({left: '-=120' }, 300,function(){
					$scroller.children().first().appendTo($scroller);
					$scroller.css('left','0px');
				});
			});

			$("#left-arrow").click(function() {
				$scroller.animate({ left : '+=120' }, 300, function() {
					$scroller.children().last().prependTo($scroller);
					$scroller.css('left','0px');
				});
			});

		}
		
	},
	wishlist: {
		init: function(){
			$(".toy_image").tooltip({
				// each trashcan image works as a trigger
				tip: '#tooltip',
				onBeforeShow: function(event) {
					var trigger = this.getTrigger(), tip = this.getTip();
					tip.find('.description').html(trigger.data('description'));
					tip.find('.product-name').html(trigger.data('product-name'));
					tip.find('#bt_more_info').attr('href',trigger.data('product-link'));
					
				},
				
				effect: 'fade',
				// move tooltip a little bit to the right
				offset: [40, 0],
				// there is no delay when the mouse is moved away from the trigger
				delay: 0.5,
				predelay: 50
			});
			$('#bt_more_info').openDOMWindow({ 
				eventType:'click', 
				width : 650,
		        windowSource:'ajax' 
			});
			
			$('#share').openDOMWindow({ 
				eventType:'click',
				width : 500,
				height: 380
			});
			
			$("#facebookLink-wishlist").click(function(){
				var url = $('#wishlist-share').data('share-link');
				mattelJS.common.fbs_click(url);
			});
			
			$("#twitterLink-wishlist").click(function(){
				var url = $('#wishlist-share').data('share-link');
				var text = $('#wishlist-share').data('share-text');
				mattelJS.common.twitter_click(url,text);
			});
			

			$("#submitBtn-wishlist").click(function(){
				var url = $('#wishlist-share').data('share-link');
				var $this = $(this);
				console.log('wish val:'+$("#wishlistEmailForm [type='text']").val());
				if($("#wishlistEmailForm [type='text']").val()){
					$.post('/wishlist/email/',{'to' : $("#wishlistEmailForm [type='text']").val() , 'url':url},function(data){
						if(data.success){
							alert($this.data('success-msg'));
						}
						$("#wishlistEmailForm [type='text']").val('');
						$.closeDOMWindow();
					});
				}
				
			});
			
			
			
			var $scroller = $('#wishlist_scroller');
			
			$("#right-arrow").click(function(){
				$scroller.animate({left: '-=120' }, 300,function(){
					$scroller.children().first().appendTo($scroller);
					$scroller.css('left','0px');
				});
			});

			$("#left-arrow").click(function() {
				$scroller.animate({ left : '+=120' }, 300, function() {
					$scroller.children().last().prependTo($scroller);
					$scroller.css('left','0px');
				});
			});
		}
	},
	
	contest: {
		registration:function(){
			
			
			var check = function(){
				var $this = $("#receive_news :input");
				if($this.is(':checked')){
					
					$("input.dob.day[value=]").val("dd");
					$("input.dob.month[value=]").val("mm");
					$("input.dob.year[value=]").val("yyyy");
					
					$("#extra_fields").show();
					$("#rulesLink").hide();
					$("#extra_fields").css( {position: 'relative', left: '0', margin: '320px 0 0 16px'} );
				}else{
					
					$("input.dob.day[value='dd']").val("");
					$("input.dob.month[value='mm']").val("");
					$("input.dob.year[value='yyyy']").val("");
					
					$("#extra_fields").hide();
					$("#rulesLink").show();
					$("#extra_fields").css( {position: 'absolute', left: '-1000'} );
				}
				
			};
			check();
			
			$("#receive_news :input").click(check);


			$('#contest_form').validate({
				debug:false,
				onsubmit: true,
				onfocusout: false,
				onkeyup: false,
				onclick: false,
		        rules: {
		            first_name: "required",
		            last_name: "required",
		            city : "required",
		            phone_0 : "required",
		            acceptTC: "required",
		            email: {
		                required: true,
		                email: true
		            }
		        },
		        showErrors: function(errorMap, errorList) {
		        	var summary = "";
		            $.each(errorList, function() {
		            	 summary += this.message + "\n"; 
		           	});
		           	if(errorList.length) alert(summary);
		        },
		        messages: {
		            first_name: gettext('Enter your first name'),
		            last_name: gettext('Enter your last name'),
		            city: gettext('Enter your city'),
		            phone_0: gettext('Enter your phone number'),
		            acceptTC: gettext('Please, certify that you are older then 13 years.'),
		            email: {
		                required: gettext('Please enter an email address'),
		                minlength: gettext('Please enter a valid email address')
		            }
		        },
		        submitHandler: function (form) {
		        	$("input.dob.day[value='dd']").val("");
					$("input.dob.month[value='mm']").val("");
					$("input.dob.year[value='yyyy']").val("");
		        	
            		form.submit();
        		}
		    });
		},
		thankyou:function(){
			$("#facebookLink-contest").click(function(){
				var url = $('#contest-thankyou').data('share-link');
				mattelJS.common.fbs_click(url);
			});
			
			$("#twitterLink-contest").click(function(){
				var url = $('#contest-thankyou').data('share-link');
				var text = $('#contest-thankyou').data('share-text');
				mattelJS.common.twitter_click(url,text);
			});
		}
		
	},
	
	toystore:{
		init: function(){
			$("#carousel_support img").slice(0,4).each(function(){
				$("#carousel").append(this);
			});
			
			var l = $("#carousel_support img").length;
			$("#carousel_support img").slice(l-2,l).each(function(){
				$("#carousel").append(this);
			});
			
			var leftClick = function(){
				var con = c.data('cloudcarousel');
				mattelJS.toystore.toy_detail();
				
				//console.log(con.frontIndex);
				var len = con.items.length / 2;
				var i = (len + con.frontIndex)%con.items.length;
				var item = con.items[i];
				
				var first = $("#carousel_support img:first").remove();
				var img = $(item.image);
				
				var clone = img.clone(true);
				
				img.attr('src',first.attr('src'))
				.attr('id',first.attr('id'))
				.attr('alt',first.attr('alt'))
				.attr('title',first.attr('title'));
				
				$("#carousel_support").append(clone);
				//Cufon.refresh();
			};
			
			var rightClick = function(){
				var con = c.data('cloudcarousel');
				mattelJS.toystore.toy_detail();
				
				//console.log(con.frontIndex);
				clearTimeout(con.showFrontTextTimer);				
				con.showFrontTextTimer = setTimeout( function(){con.showFrontText();},300);
				
				var len = con.items.length / 2;
				var item = con.items[(len + con.frontIndex)%con.items.length];
				
				var last = $("#carousel_support img:last").remove();
				var img = $(item.image);
				
				var clone = img.clone(true);
				
				img.attr('src',last.attr('src'))
				.attr('id',last.attr('id'))
				.attr('alt',last.attr('alt'))
				.attr('title',last.attr('title'));
				
				$("#carousel_support").prepend(clone);
				
			};
			
			var storeIndex = function(){
				var con = c.data('cloudcarousel');
				if(con.frontIndex < 0){
					var item = con.items[con.items.length + con.frontIndex];
				} else {
					var item = con.items[con.frontIndex];
				}
				$('.bt_more_info').attr('href','/toy/'+item.image.id);
				$('.bt_wish_add').attr('href','/wishlist/add/'+item.image.id);
				
				$('.rankWrap').load('/toy/rank/'+item.image.id);
				//console.log(item.image);
				
				$.cookie('toystore', item.image.id, { expires: 7, path: '/' });
				
			}
			
			
			// This initialises carousels on the container elements specified, in this case, carousel1.
			c = $("#carousel").CloudCarousel({			
					xPos: 500,
					yPos: 120,
					buttonLeft: $("#right-but"),
					leftClick: leftClick,
					buttonRight: $("#left-but"),
					rightClick: rightClick,
					storeIndex: storeIndex,
					altBox: $("#alt-text"),
					titleBox: $("#title-text"),
					init: function() {
						$('.activeToyContainer').appendTo($('#carousel > div')).show();					
					}
			});
			
			$('.bt_more_info').openDOMWindow({ 
				eventType:'click', 
				width : 650,
		        loader:0, 
		        windowSource:'ajax' 
			});
			
			var toy_id = $("#canvas").data('toy-id');
			$('.rankWrap').load('/toy/rank/'+toy_id);
		},
		toy_detail: function(){
			$('.rankWrap').show();
			$("#carousel img:first").css('visibility','');
			$(".activeToyContainer").show();
			$(".toyStoreLanding").hide();
			$(".exploreCopy").hide();
		},
		show: function(){
			$('.rankWrap').hide();
			$("#carousel img:first").css('visibility','hidden');
			$(".activeToyContainer").hide();
			$(".toyStoreLanding").show();
			$(".exploreCopy").show();
		}
	},
	games:{
		init:function(){
			if((navigator.userAgent.match(/iPhone/i)) || 
				(navigator.userAgent.match(/iPod/i)) || 
				(navigator.userAgent.match(/iPad/i))) {
					
				$('.gamePageContainer').hide();
				$('.contentPageContainer').show();
			}
		}
	}
		
	
	

};

UTIL = {
	exec: function(controller, action) {
		var ns = mattelJS,
			action = (action === undefined) ? "init" : action;

		if (controller !== "" && ns[controller] && typeof ns[controller][action] == "function") {
			console.log('firing: mattelJS.' + controller + '.' + action);
			ns[controller][action]();
		}
	},

	init: function() {
		var body = document.body,
			controller = body.getAttribute("data-controller"),
			action = body.getAttribute("data-action");

		UTIL.exec("common");
		UTIL.exec(controller);
		UTIL.exec(controller, action);
	}
};

$( document ).ready( UTIL.init );
