Navigation = {
	init:function() {
		var self = this;
		//universal nav icon and submenu class assignment
		$("nav#uniNav ul:first").children("li").each(function(i){
			//if ie
			if (!jQuery.support.opacity) {
				$(this).addClass("nth-child"+(i+1))
				if ( $(this).children("a").children("span").get(0) ){
					$(this).children("a").children("span").each(function(n){
						$(this).addClass("nth-child"+(n+1))
					})
				}
			}
			//adding 'hasSub' to parent <li> of submenu
			if ( $(this).children("ul").get(0) ){
				$(this).addClass("hasSub");
			}
		})
		//  fade/load FORMS
		 // redirect to open login form
		$("nav#uniNav ul li.login").click(function(event) {
			if($("article div#modal").length) return;
			Modal.join($("a",this).attr("href"),$("a",this).siblings("link[rel=redirect]").attr("href"));
			return false;
		});
		
		$("li.modal").click(function(event) {
			if($("article div#modal").length) return;
			Modal.join($(this).find("a").attr("href"),$(this).find("a").siblings("link[rel=redirect]").attr("href"));
			return false;
		});
		
		$("a.modal").click(function(event) {
			if($("article div#modal").length) return;
			Modal.join(this.href, $(this).siblings("link[rel=redirect]").attr("href"));
			return false;
		});
		
		Form.init();
		Modal.init(); // init related systems
	}
}

Modal = {
	redirect:null,
	
	xhr:undefined,
	
	init: function() {
		/* uncomment to make modal close when background is clicked
		$("#modal > .content > .background").click(function(event) {
			Modal.hide();
		});
		*/
		
	},
	
	join:	function(url,redirect) {
		Modal.redirect = redirect;
		Modal.show( function(e) { Modal.load(url + "?ajax") }); // show loader
	},
	
	show: function(onComplete) {
		$.scrollTo(0,300,{axis:'y'});
		
		if(Device.can_touch) $("li.video").children().addClass("hidden");
		
		$("#modal").addClass("on").removeClass("off").css({"height":($("article").height() + 38),"top":$("article").position().top}).fadeIn();
		
		$("#modal > .content > .background").animate({
			opacity:".90"
		},425,"easeInOutQuad", onComplete);
	},
	
	hide: function() {
		if(Modal.xhr !== undefined) { Modal.xhr.abort(); } 
		$("#modal > .content > .form").fadeOut("fast", function(event) {			
			$("#modal > .content > .background").animate({opacity:"0"},425,"easeInOutQuad", function() {
				$("#modal").removeClass("on").addClass("off");
				$("#modal > .content > .form").removeClass("formSent");
				if(Device.can_touch) $("li.video").children().removeClass("hidden");
			});
		});
	},
	
	load: function(url) {
		if(Modal.xhr !== undefined) { Modal.xhr.abort(); } 
		Modal.xhr = $.ajax({
			type: 'GET',
			url: url,
			success: function(data) {
				$("#modal > .content > .form").html(data).fadeIn("fast").width($("#modal > .content > .form > div").outerWidth());
				$("#modal > .content > .form .closeModal, .closeModalButton").live('click',function(e) {
					Modal.hide();
					return false;
				});
				Form.init();
			}
			
		});
	},
	
	insert:function(form) {
		$("#modal > .content > .form").removeChildren().append(form);
		Modal.show();
	}
}

Form = {
	
	error:function(data, target) {
		$("form .error").remove();
		var theURL = target.attr("action");
		var formID = target.attr("id");
		if ( data.indexOf("errorlist") != -1 ){ //error exists in the response
			var error = $(data).find(".errorlist");
			$(error).each(function(){					
				errorMSG = $(this).children("li").text();
				labelFor = $(this).siblings("label").attr("for");
				$("form#"+formID+" #" +labelFor).parent().append('<span style="top:20px;left:-25px;" class="icon error" title="'+errorMSG+'">'+errorMSG+'</span>');				
			})
			return true;
		}
		
		return false;
	},
	
	init:function(){
		$(".stand-alone .closeModal").hide();
		$("input[type=checkbox], input[type=radio]").checkBox();
		if ( $("select").get(0) ){
			$("select").each(function(){
				var select = $(this);
				if ($(this).is(":visible") && $(this).hasClass("noStyle")!=true ) { //if not hidden or already beautified :)
					$(this).msDropDown();
				}
			})
		}
		if($("form#register").length && (Device.get_cookie("age_gate")=="failed")) {
			$("form#register").find("#id_submit").parent().empty().append('<p>We can not register you at this time, please refer to the Polaroid <a href="/en/terms" title="Terms & Conditions">Terms & Conditions</a> for more information.</p>');
		}
		
		$("form.ajaxForm").submit(function(event){
			event.preventDefault();
			$("form .error").remove();
			
			var form = $(this);
			theURL = $(this).attr("action") + "?ajax";
			formID=$(this).attr("id");
			formData = $(this).serialize();
			
			if($(this).attr("id")=='register') { // there should be a way to feed in an ONSUBMIT, ONERROR, custom function here
				if(!Form.check_age($(this).find("#id_birthday_month").val() + " " + $(this).find("#id_birthday_day").val() + ", " + $(this).find("#id_birthday_year").val())) {
					$(this).find("#id_submit").parent().empty().append('<p>We can not register you at this time, please refer to the Polaroid <a href="/en/terms" title="Terms & Conditions">Terms & Conditions</a> for more information.</p>');
					return;
				}
			}
			
			var orgTxt = form.find(".submit").val();
			form.find(".submit").val("Sending...");
			
			$.ajax({
				url: theURL,
				type: 'POST',
				data: formData,
				//success: Form.error(data, form)
				success: function(data) {
					
					form.find(".submit").val(orgTxt);
					
					if ( data.indexOf("errorlist") != -1 ){ //error exists in the response
						var error = $(data).find(".errorlist");
						$(error).each(function(){					
							errorMSG = $(this).children("li").text();
							labelFor = $(this).siblings("label").attr("for");
							$("form#"+formID+" label[for|=" +labelFor+"]").append('<span style="" class="icon error" title="'+errorMSG+'">'+errorMSG+'</span>');
						})
						
					} else if ( data.indexOf("message") != -1 ){						
						switch(form.attr("id")) {
							case 'retrieve-password':
								form.find(".message-relay").html($(data).find(".message")).addClass("on");
								form.find(".submit").val("Check Your Email").attr("disabled","disabled");
								break
							case 'change-password':	
								form.find(".message-relay").html($(data).find(".message")).addClass("on");	
								form.find(".submit").val("Password Changed").attr("disabled","disabled");
								break;
							default:
								form.parents(".modal").parent().html(data);
								return;
						}
					}else {
						var redirect = (Modal.redirect != null) ? Modal.redirect : form.find("link[rel=redirect]").attr("href");
						if(redirect) location.href=redirect;
						else  location.reload(); // fail safe just reload the page or direct to new page
					}
				}
			});
		}).find("input[type=submit]").removeAttr("disabled");
	},
	
	check_age: function(dateStr) {
		if(Device.get_cookie("age_gate")=="failed") return;
		var rd = new Date(Date.parse(dateStr))
		var d = new Date();
		var age = d.getYear() - rd.getYear();
		if(d.getMonth() < rd.getMonth() || (d.getMonth() == rd.getMonth() && d.getDate() < rd.getDate()) ) age--;
		if(age < 13) {
			Device.set_cookie("age_gate","failed",3600);
			return;
		}
		return true;
	}
}


/**
*	
*/
var Device = {

	init: function() 
	{
		// Touch screen specific functionality + stlying for tablets and mobile
		if(this.can_touch) { 
			$(window).ready(this.remove_toolbar);
			
			$(window).bind("orientationchange", this.setorientation);
			this.setorientation();
		}
		
		var targ = $("header nav > ul > li:nth-child(6) a"); // rainbow text on nav
		var text = targ.text().split("");
			targ.empty();
		for(var i = 0; i < text.length; i++) {
			$("<span>"+text[i]+"</span>").appendTo(targ);
		}
		
		$(".extend-grid").each(function(i,e) {	// 2. extend-grid-button component TODO Move to module level
			var classes = $(this).attr('class').split(' ')
			var numDots = Device.getClassValue(classes,"dots");
			numDots = (numDots) ? numDots : 10;
			for(var n=0; n < numDots; n++) {
				$(this).append("<div></div><div></div><div></div><div></div>");
			}
		});
	},
	
	
	is_ie:function() {
		return (!jQuery.support.opacity); // true ie, false not ie
	},
	
	/**
	* Determine if device is touch-capable
	*/
	can_touch: ('createTouch' in document),
	
	/**
	*	Scroll past location bar on iPhone 
	*/
	remove_toolbar: function() 
	{
		$.scrollTo('+=0px',100,{axis:'y'}); //scrolls 0px..but removes the toolbar on iphone
	},
	
	setorientation:function ()
	{
		$('meta[name=viewport]').remove(); // clear meta 
		if(screen.height >= 1024 || screen.width >= 768) { // tablet
			if(Math.abs(window.orientation)==90) {// horizontal // note that the device-width/device-height are REVERSED for horizontal layout
				$('<meta name="viewport" content="width=device-height, height=device-width, initial-scale=1, maximum-scale=.92, minimum-scale=.92, user-scalable=no"/>').appendTo($("head")); 	
			} else {
				$('<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=.72, minimum-scale=.72, user-scalable=no"/>').appendTo($("head")); // vertical
			}
		}else { // mobile
			if(Math.abs(window.orientation)==90) {
				$('<meta name="viewport" content="width=device-height, height=device-width, initial-scale=1, maximum-scale=.4, minimum-scale=.4,  user-scalable=yes"/>').appendTo($("head")); 
			} else {
				$('<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=.3, minimum-scale=.3, user-scalable=yes"/>').appendTo($("head")); // vertical
			}
		}
	},
	
	log: function(msg) { 
		if(typeof(console) !== 'undefined' && console != null) console.log(msg); 
	},
	
	getClassValue: function (classes,string,isString){
		var temp = 0; var pos = string.length;
		for (var j=0;j<classes.length;j++) {
			if (classes[j].indexOf(string) == 0) {
				temp = classes[j].substring(pos);
				break;
			}
		}
		return (isString) ? temp : Math.max(0,temp);
	},
	
	querystring:function( name ) {
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( window.location.href );
	  if( results == null ) return "";
	  else return decodeURIComponent(results[1].replace(/\+/g, " "));
	},
	
	set_cookie: function setCookie(c_name,value,expireseconds) {
		var exdate=new Date();
		exdate.setSeconds(exdate.getSeconds()+expireseconds);
		document.cookie=c_name+ "=" +escape(value)+
		((expireseconds==null) ? "" : ";expires="+exdate.toUTCString());
	},
	
	get_cookie: function getCookie(c_name)  {
		if (document.cookie.length>0) {
			c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1) {
				c_start=c_start + c_name.length+1;
				c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1) c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
				
			}
		}
		return "";
	}

}


Page = {
	o: {
		max				:false,
		page_data		:null,
		width			:Number(0),
		targ			:null,		// scrolling target
		sorting			:false		// for admin reordering
	},
	
	init:function(slug,page_data) {
		this.o.page_data = page_data;
		this.o.targ = $("section");
		
		// 1. clearing
		this.clear_unused_modules();
		// 2. resizing
		$("img.flow").bind("load",function(event) { Page.resize(); }); // not sure if we need to resize after every image load
		$(document).ready(function(event) { Page.resize();});
		this._scroller();
		this.resize();
		// 3. page specific functions
		// TODO, if each page has its own template, reverse with Page.Home.init() which would call Page.init()
		
		Device.log("init the " + slug);
		switch(slug) {
			case 'home':
				Page.Index.init();
				Page.onScrollComplete($("article"), $("section"), this.load_next_page); // onscrollcomplete load next page
				break;
			case 'blog':
				Page.Blog.init();
				break;
			case 'search':
				Page.Search.init();
				break;
		}
		
		Page.reset();
		window.setTimeout(function() { Page.reset(); }, 1000); //
		window.setInterval(function(){  Page.reset(); }, 4000); // failsafe reset for layout, consider adding to 1000 interval
		
		if($(".admin-panel").length && typeof(Admin) != 'undefined') { Admin.init(); }
		
		/* setTimeout(function() { // for testing pagination of modules
			$("section").children().remove();
			Page.load_next_page() 
		}, 2000); */
		
	},
	
	/* load next page of modules */
	load_next_page:function(e) {
		
		var o = Page.o.page_data;
		o.current_page++;
		if(o.page_count >= o.current_page) { // next page exists, request it
			$.get(("?ajax&page="+(o.current_page)+"&per_page="+(o.per_page)), function(data) {
				$("section").append(data);
				Page.scroller.setValue(0);
				Page.reset();// max width
			});
		}else { // kill scroll pagination
			$("article").unbind("scroll");
		}
	},
	
	scroller:null,
	_scroller:function() {		
		var mask = $("article");
		var content = $("section");
				
		if(content.length) {
			this.scroller = new Dragdealer('site-slider', {
				speed:20,
				horizontal: true,
				vertical: false,
				xPrecision: content.outerWidth(),
				mask:mask,
				content:content,
				animationCallback: function(x, y) {
					mask.scrollLeft(x*(content.outerWidth()-mask.outerWidth()));
				},
				animationComplete: function() {
					
				}
			});
			if(Device.can_touch) mask.jScrollTouch(false,this.scroller);
		}


		var resizeTimer = null;
		$(window).bind('resize', function() {
			if(Device.is_ie()) { // 
				$(".scrollbar-container").css("width","0px");
				$("#scrollarea").css("width","auto");
				$(".scrollbar-container").width(mask.width() - $("#scrollarea").width());
				$("#scrollarea").css("width","100%");
			}
			
			if(!content.length) return;
			$("#site-slider .handle").width( ((mask.width()/content.width()) * $("#site-slider").width()) -  12);
			
			if(Page.scroller) Page.scroller.documentResizeHandler();
			
			if(mask.width()/content.width()>=1) $("#scrollbar").addClass("hidden");
			else $("#scrollbar").removeClass("hidden");
			
		});
		

	},
	
	/* onScrollComplete lazy load pagination */
	onScrollComplete:function(mask, content, callBack) {
		var scrollCompleteTimer = null;
		mask.bind("scroll", function(e) {
			if (scrollCompleteTimer) clearTimeout(scrollCompleteTimer);
			scrollCompleteTimer = setTimeout(function() {
				if(mask.scrollLeft() + mask.width() >= content.width() && callBack && typeof(callBack) == "function") callBack(e); // if reached end of scrolled content
			}, 500);
		});
	},
	
	clear_unused_modules:function() {
		$(".module").each(function(i) {
			if($(".content",$(this)).length == 0) $(this).remove();
		});
	},
	
	reset:function() {
		this._setWidth(999999);// max width
		this.resize(false);
		this.attach_scroll_wheel();
	},
	
	attach_scroll_wheel:function() {
		if(!Device.can_touch) {
			if($("body").width() <= $(window).width() && $("body").height() <= $(window).height()) {
				if(!this.o.mousewheel_attached) {
					this.o.mousewheel_attached = true;
					$(document).mousewheel(function(event, delta, deltaX, deltaY) {
						Page.scroller.scrollToDelta(Math.round(delta*500),0);
					});
				}
			}else {
				this.o.mousewheel_attached = false;
				$(document).unmousewheel();
			}
		}
	},
	
	resize: function(max) {
		
		if(!this.o.targ) this.init();
		if(max != undefined)this.o.max = max; //Bool to lock to max width found (for animating widths)
		this._setWidth(this._getWidth());
		$(window).trigger("resize");
	},
		
	_getWidth:function() {
		var width = 30;
		$(".module").each(function(i,e) { // get total width in pixels of module area
			width += $(this).outerWidth(true);
		});
		this.o.width = width;
		return width;
	},
	
	_setWidth:function(w) {
		if(this.o.max && w < parseInt(this.o.targ.css('width'))) return; // if max, dont resize down
		this.o.targ.css('width',w); 	//set section width
	}
		
}


Page.Index = {
	o : {},
	
	init:function() {
		// create a button for each module
		var resizeTimer = null;
		$(window).bind('resize', function() {
			if (resizeTimer) clearTimeout(resizeTimer);
			resizeTimer = setTimeout(function() {
				if(!Page.o.sorting && (!Page.Index.o.aw || Page.Index.o.aw != $("article").width() || Page.Index.o.sw != $("section").width())) {
					Page.Index.module_buttons();
					Page.Index.o.aw = $("article").width();
					Page.Index.o.sw = $("section").width();
				}
			}, 100);
		});
		Page.scroller.disableContainerClick();
	},
	
	module_buttons:function() {
		var container = $("#scrollarea #scrollbar #site-slider");
		//$(".module-button",container).remove(); // clear
		$("article section .module").each(function(index,value) {
			var mod = $(this);
			$('<div title="'+mod.find("a.module-title").attr("title")+'"/>').html('<div class="arrow"></div><div class="arrow right"></div>')
				.addClass("module-button")
				.prependTo(container)
				.css("left",(10 + ( (  (mod.position().left + ( mod.outerWidth()/2)) / mod.parent().outerWidth()) * container.width())      ) )
				.click(function(e) {
					Page.scroller.setValue((mod.position().left + 30)/($("section").width()),0,false);
					return false;
				})
				.mouseover(function(e) {
					$(this).find(".arrow").css("border-color","transparent #fff");
				})
				.mouseout(function(e) {
					$(this).find(".arrow").css("border-color","transparent " + Device.getClassValue(mod.attr('class').split(' '),"color",true));
				})
				.find(".arrow").css("border-color","transparent " + Device.getClassValue(mod.attr('class').split(' '),"color",true))
		});
	}
	
}

Page.Blog = {
	row:"row1",
	init:function() {

		var target = $(".post-detail");	
		
		if(!target.length) {
			$(".posts .action-menu a.toggle").click(function(e) {
				$(".expandable").hide();// hide all expandables
				$(".flag-container").appendTo($(this).parent()).show().find("form").attr("action",$(this).attr("href")+"?ajax");
				return false;
			});
			$(".expandable li.toggle-cancel").click(function(e) {
				$(this).parents(".expandable").hide();
				return false;
			});
			this.flag($(".flag-container"));
		}else {
			Module.pagination(target, "comment", this.template);
			Module.toggle(target, $(".action a.toggle",target), 
				function() { 
					$("#blog-page .comment-box").css("min-height","530px"); 
				}, 
				function() { $("#blog-page .comment-box").css("min-height","370px");} 
			); // leave a comment form
			Module.Comments.submit_comment(target);
			Module.Comments.config_flag(target);
		}
	},
	
	/* template used to load new comments using ajax */
	template:function(target, comments) {
		var expandable = $(".expandable.flag",target);
		var ul = $("ul.comments");
		for(var i = 0; i < comments.length; i++) {
			var name = comments[i].user.first_name + " " + comments[i].user.last_name.charAt(0) + ".";
			var avatar = comments[i].user.avatar; avatar = (avatar) ? avatar : "http://c0026181.cdn1.cloudfiles.rackspacecloud.com/uploads/avatars/default_avatar.png";
			
			var li = $("<li/>").appendTo(ul).addClass("comment-content clearfix " + Page.Blog.row);
			$("<div/>").appendTo(li).addClass("avatar").append( ((avatar) ? '<a href="/en/movement/'+ comments[i].user.id + '" title="'+name+'"><img src="'+avatar+'"/></a>' : ''));
			$("<div/>").appendTo(li).addClass("author").html('<a href="/en/movement/'+ comments[i].user.id + '" title="'+name+'">'+name+'</a>');
			$("<div/>").appendTo(li).addClass("date").html(comments[i].created);
			li.append(comments[i].body);

			Page.Blog.row = (Page.Blog.row == "row1") ? "row2" : "row1";
			
			/* add the delete x flag buttons */
			if(expandable.length) {
				$('<div class="flag"/>').appendTo(li).append('<a href="/en/social/flag/comment/'+comments[i].id+'?ajax" class="toggle" title="Flag Comment"><img src="/media/img/icons/flag.png"/></a>');
			}
		}
	},
	
	flag:function(target) {
		$(".flag li.toggle-confirm",target).click(function(e) { return $("form#flag_form").submit(); });
		$("form#flag_form").submit(function(e) {
			$(this).parents(".action-menu").find(".favorite-loader").fadeIn(500);
			$.post($(this).attr("action"),$(this).serialize(), function(data) {
				$(".flag",target).parents(".action-menu").delay(1000).fadeOut(500, function() {});
			});
			return false;
		});
	}
	
}

Page.Search = {
	init:function() {
		this.pack("artist");
		this.pack("movement");
		this.pack("product");
		this.pack("post");
	},
	pack:function(container) {
		var ul = $("div.module.search ul."+container+"-container"); // ARTISTS
		if(ul.length) {
			ul = $(ul[0]).removeClass(container+"-container");
			$("div.module.search li."+container).each(function() {
				ul.append($(this));
			})
			$("div.module.search ul."+container+"-container").parents(".module").remove();
		}
	}	
}

var Video = {
	init:function() 
	{
		this.flashvars = {};
		this.params = { wmode: "transparent", allowfullscreen: "true", allowscriptaccess: "always" };
		this.attributes = {};
		this.expressinstall = "http://www.treacheryisafoot.com/wp-content/plugins/vipers-video-quicktags/resources/expressinstall.swf";
	}
}
Video.init();
