var form = document.getElementById('dialog-form');
if (form) {
	form.style.display = 'none';
}


/* =========================
 * Share Section
 * ========================= */
$('.popup').live('click',function(){
	_gaq.push(['_trackEvent', 'share_links', $(this).text(), $(this).attr('data-share_url')]);
	newwindow = window.open($(this).attr('href'),'Share This','menubar=0,width=550,height=400');
	return false;
});

var ghost = {
	g_class: '',
	g_val: '',
	init: function(opts){
		var self = this;
		
		if (!opts) {
			//log('No elements defined.');
			return false;
		}
		
		this.g_class = opts.g_class || 'ghost';
		this.g_val = opts.g_val || 'data-placeholder';
		
		for (var i=0; i < opts.elements.length; i++) {
			var name = opts.elements[i],
				$el = $('input[name=' + name + ']');
			if ($el.length) {
				// Create container element
				$container = $('<div />').addClass(self.g_class).css({'position':'relative','z-index':1});
				// insert container into dom
				$el.before($container);
				// move original element there
				$el.appendTo($container).css({'position':'relative','z-index':2});
				// create new label
				$label = $('<label />').text($el.attr(self.g_val)).css({'position':'absolute','z-index':3}).attr('data-by','ghost');
				// move label in container
				$el.before($label);
				
				// Focus handler
				$el.focus(function(){
					var v = $.trim($(this).val()),
						p = $(this).attr(self.g_val),
						$l = $(this).parent().find('label[data-by=ghost]');
					if (!v.length) {
						$l.hide();
						$(this).val('');
					}
				});
				$el.keydown(function(e){
					$l = $(this).parent().find('label[data-by=ghost]');
					if (e.which != 8) {$l.hide();}
				});
				$label.click(function(){$(this).parent().find('input').focus();});
				
				// Blur handler
				$el.blur(function(){
					var v = $.trim($(this).val()),
						p = $(this).attr(self.g_val),
						$l = $(this).parent().find('label[data-by=ghost]');
					if (!v.length) {$l.show();}
				});
			} else {
				//log("'" + name + "' isn't a valid input name.");
			}
		};
	}
}
var newsletter = {
	el: $('#mail_chimp'),
	email: '',
	data:'',
	init: function(){
		
		ghost.init({
			elements: ['email']
		});
		
		var context = this;
		this.el.submit(function(){
			this.data = '';
			context.on_submit();
			return false;
		})
	},
	on_submit: function(){
		$('label.error').remove();
		if (this.validateForm()) {
			var fields = this.el.find('input'),
				temp = '&categories=';
			
			for (var i=0; i < fields.length; i++) {
				var field = fields[i];
				if (field.name == 'email') {
					this.email = field.value;
					this.data = 'email='+field.value;
				} else if (field.name == 'interest' && $(field).is(':checked')) {
					temp += field.value + ',';
				}
			};
			this.data += temp.slice(0, -1);
			this.send_to_mailchimp();
		}
	},
	send_to_mailchimp: function(){
		// ajax info to special php page so that it can post to mailchimp
		//console.log('data sent');
		//console.log(this.data);
		var context = this;
		$.ajax({
			type: "POST",
			url: "/js/mcapi_listSubscribe.php",
			data: context.data,
			dataTypeString: 'json',
			success: function(data) {
				//console.log(data);
				if (data.status) {context.on_success(data);} else {
					data.id = 'email';
					// Respond to Error
					if (data.error_code == 214) {
						data.message = context.email + " has already subscribed to Flavorchem's newsletter.";
						//console.log(context);
					}
					context.on_error(data);
				}
			},
			error: function(data) {
				alert('Something went wrong. Please try again.');
			}
		});
	},
	on_success: function(data){
		$('label.error').remove();
		var container = $('<div />').addClass('mc-response');
		$('<h3 />').text('Success').appendTo(container);
		$('<p />').text(data.message).appendTo(container);
		$(this.el).html(container);
	},
	on_error: function(data){
		// console.log(data);
		$('#'+data.id).after('<label for="' + data.id + '" class="block on_error error">' + data.message + '</label>');
		return false;
	},
	email_regexp: /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,
	validateForm: function() {
		var error = 0;
		if (!(this.email_regexp.test($('input[name=email]').val()))) {
			this.on_error({
				id: 'email', 
				message: 'A valid email is required.'
			});
			error = 1;
		}
		if (!$('input:checked').length) {
			this.on_error({
				id: 'interests', 
				message: 'An interest is required.'
			});
			error = 1;
		}
		if (error){return false;}
		return true;
	}
}

var emailClass = {
	context: this,
	el: $("#dialog-form"),
	trigger: $('.share_email'),
	form: $(this.el).find('form'),
	success_msg: $(this.el).find('.success_msg'),
	name: $("#name"),
	from_email: $( "#from_email" ),
	to_email: $( "#to_email" ),
	msg: $( "#msg" ),
	hp: $( "input[name=hp]" ),
	allFields: $('#dialog-form input:visible,#dialog-form textarea'),
	bValid: false,
	messageData: function(){
		var self = this;
		return encodeURI('<table style="margin:10px;">' + 
		'<tr><td style="padding:10px;"><strong>Name:</strong></td><td style="padding:10px;">' + self.name.val() + '</td></tr>' + 
		'<tr><td style="padding:10px;"><strong>Email:</strong></td><td style="padding:10px;">' + self.from_email.val() + '</td></tr>' + 
		'<tr><td style="padding:10px;"><strong>Message:</strong></td><td style="padding:10px;">' + self.msg.val() + '</td></tr>');
	},
	email_regexp: /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,
	checkLength: function(o) {
		if (!o.val().length) {
			o.addClass( "ui-state-error" )
			.after('<label for="' + o.attr('id') + '" class="error">This field is required.</label>');
			return false;
		} else {
			return true;
		}
	},
	checkRegexp: function(o) {
		if ( !( this.email_regexp.test( o.val() ) ) ) {
			o.addClass( "ui-state-error" )
			.after('<label for="' + o.attr('id') + '" class="error">A valid email is required.</label>');
			return false;
		} else {
			return true;
		}
	},
	init: function() {
		var self = this;
		this.on_dialog();
		this.trigger.live('click',function() {
			self.msg.val($(this).attr('data-msg'));
			self.el.dialog("open");
			_gaq.push(['_trackEvent', 'share_links', $(this).text(), $(this).attr('data-share_url')]);
			return false;
		});
		this.on_dialog_blur();
	},
	on_dialog: function() {
		var self = this;
		self.el.dialog({
			autoOpen: false,
			width: 560,
			modal: true,
			context: self,
			open: function(event) {
				self.on_dialog_open(event, self);
			},
			close: function(event) {
				self.on_dialog_close(event, self);
			}
		});
	},
	on_dialog_open: function(event, self) {
		self.el.find('.success_msg').hide();
		
		self.el.find('form').submit(function(){
			self.allFields.removeClass( "ui-state-error" );
			$('label.error').remove();
			
			self.bValid = self.checkLength(self.name) || false;
			self.bValid = self.checkLength(self.msg) || false;
			self.bValid = self.checkRegexp(self.from_email) || false;
			self.bValid = self.checkRegexp(self.to_email) || false;
			
			if (self.bValid) {
				$.ajax({
					url: "/js/emailClass.php",
					data: 'name='+self.name.val()+'&from='+self.from_email.val()+'&to='+self.to_email.val()+'&subject='+self.name.val()+' wanted to share this with you&hp='+self.hp.val()+'&message='+self.messageData(),
					type: 'POST',
					dataType: 'json',
					context: self,
					success: self.on_ajax_success
				});
			}
			return false;
		});
	},
	on_dialog_close: function(event, self) {
		$('label.error').remove();
		self.allFields.val( "" ).removeClass( "ui-state-error" );
		self.el.find('form').show();
		self.el.find('success_msg').hide();
	},
	on_ajax_success: function(data) {
		if (data.success) {
			this.el.find('.success_msg').show();
			this.el.find('form').removeAttr('style').hide();
		} else {alert(data.msg);}
	},
	on_dialog_blur: function() {
		var self = this;
		$('.ui-widget-overlay').live("click", function() {self.el.dialog("close");});
	}
	
}


//jQuery Starter
$(document).ready(function() {
	emailClass.init();
	newsletter.init();
	$('html').removeClass('no-js').addClass('js');
	
	//Theme Control
	var themes = ['orange', 'olive', 'vanilla'];
	if(localStorage.getItem('theme') == null){
		localStorage.setItem('theme', themes[0]);
	} else if(location.pathname == "/index.php" || location.href == "http://"+location.hostname+"/"){
		var themeIndex = themes.indexOf(localStorage.getItem('theme'));
		if(themeIndex != themes.length-1){localStorage.setItem('theme',themes[themeIndex+1]);} else{
			localStorage.setItem('theme', themes[0]);
		}
		
	}
	$("body").attr('id',localStorage.getItem('theme'));
	
	$(".fourhundred p:first").css({"font-size": "16px", "line-height": "22px"});
	
	$('.sideNav li a').wrap('<div/>');
	$('.sideNav li div').prepend('<span/>');
	$('.sideNav li').has('ul').children('div').children('span').addClass('sideNavToggler');
	$('.sideNav li').not('.here, .parent-here').find('ul').hide();
	

	
	$('.sideNavToggler').each(function(){
		if($(this).parent().parent().is('.here, .parent-here')){$(this).addClass('open');}
	});
	
	$('.sideNavToggler').live('click', function(e){
		e.preventDefault();
		$(this).parent().parent().children('ul').toggle();
		$(this).toggleClass('open');
	});	
	
	$('#nav-sub .sideNavToggler').closest('.sideNav').addClass('has_children');
});

//ARRAY.indexOf for Internet Explorer
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}



//simpleStorage
(function(){var k=this;if(!k.localStorage&&navigator.cookieEnabled){var x="storageData_",y="++",z="::",l=function(a,c,b){var e=new Date;e.setTime(e.getTime()+b);b="; expires="+e.toGMTString();document.cookie=a+"="+c+b+"; path=/"},h=function(a){a=a+"=";for(var c=document.cookie.split(";"),b=0,e=c.length;b<e;b++){for(var d=c[b];d.charAt(0)==" ";)d=d.substring(1,d.length);if(d.indexOf(a)===0)return d.substring(a.length,d.length)}return null},m=function(a){l(a,"",-1)},i=function(){for(var a="",c=0;h(y+c)!==null;)a+=h(y+
c++);return a==""?[]:a.split(y)},n=function(a){for(var c=Math.ceil(a.length/4E3),b=0;b<c||h(y+b)!==null;){b<c?l(y+b,a.substr(b*4E3,(b+1)*4E3>a.length?a.length-b*4E3:4E3),2592E3):m(y+b);b++}},f=k.localStorage={length:0,setItem:function(a,c){var b=i(),e=0,d=b.length,g=false;for(e=0;e<d;e++){var j=b[e].split(z);if(j[0]==a){j[1]=c;g=true;b[e]=j.join(z);e=d}}if(!g){b.push(a+z+c.replace(/::/g,": :").replace(/\+\+/g,"+ +"));this.a.push(a);this.length++}n(b.join(y))},
getItem:function(a){var c=i(),b=0,e=c.length;for(b=0;b<e;b++){var d=c[b].split(z);if(d[0]==a&&d[1])return d[1]}return null},removeItem:function(a){var c=i(),b=0,e=c.length,d=false,g=[];for(b=0;b<e;b++)if(c[b].split(z)[0]!=a)g.push(c[b]);else d=true;if(d){n(g.join(y));o()}},clear:function(){for(var a=0;h(y+a)!==null;)m(y+a++);this.a=[];this.length=0},key:function(a){return a<this.length?this.a[a]:null},a:[]},o=function(){f.a=i();for(var a=0;f.a[a];)f.a[a]=f.a[a++].split(z)[0];
f.length=f.a.length};o()}})();
