function Control(type){
	var self = this;
	this.root = jQuery('#container');
	new Flash_swich();
	this.loaderChoose = function()  {
		if (self.root.find('#navi').hasClass('navi'))  
			self.nav = new Navi(self.root.find('#navi'));
		
		if (self.root.find('#emailer').length > 0)
			self.email = new Emailer(self.root.find('#emailer'));
		self.jaxChoose();
		if (self.root.children("#content").height() < 600)
			 self.root.children("#content").height(600)
		jQuery('.jax_foot').css('top', self.root.children("#content").height() + 200);
		self.pipeExtend = jQuery('.jax_pipe_xtend');
		self.pipeExtend.height((self.root.children("#content").height() + self.root.children("#content").position().top) - self.pipeExtend.position().top + 250);
		
	}
	
	this.jaxChoose = function()  {	
		if (self.root.find('.product').hasClass('list'))  
			self.productList = new ProdList(self.root.find('.product.list'));
		
		if (self.root.find('.product').hasClass('detail'))
			self.productDetail = new productDetail(self.root.find('.product.detail'))
			
	}
	if (type == 'jax') 
		this.jaxChoose();
	else 
		this.loaderChoose();
}


function productDetail(element)  {
	var self = this;
	this.root = element;
	jQuery('#printer').show();
	new jZoomer(this.root.find('#product_photo'));
	if (this.root.find('#tabber').hasClass('tabber'))  
		this.nav = new Tabb(this.root.find('#tabber'));
	new ProductViewer();
	if (this.root.find('.colors').length > 0)
		this.colorTips = new ColorTips(this.root.find('.colors').children('li'));
	this.lineBreakFix = this.root.find('h3:first').html();
	this.lineBreakFix = this.lineBreakFix.replace(/T-shirt/, '<i> T-shirt </i>');
	this.root.find('h3:first').html(this.lineBreakFix);
}

function ColorTips(element)  {
	var self = this;
	this.root = element;
	jQuery.ajax({
		url:"/tooltip",
		async: false,
		success: function(html)  {
			for (var i=0; i < self.root.length; i++) {
				var colorToTip = jQuery(self.root[i]);
				new ToolTip(html, colorToTip, colorToTip.find('input').val().replace(/ /g, '_'), true);
			};
		}
	});
}

function jZoomer(element)  {

	new Image_Zoom({
		xzoom: 250, //zooming div default width(default width value is 200)
		yzoom: 350, //zooming div default width(default height value is 200)
		offset: 20, //zooming div default offset(default offset value is 10)
		position: "right", //zooming div position(default position value is "right")
		source: "product"
	}, element);

}


function Flash_swich()  {

	var flashvars = {};
	var params = {
	  menu: "false",
	  wmode: "transparent"
	};
	var attributes = {
	  name: ""
	};

	params.flashvars = jQuery('#flash_jax_head').attr('title');

	swfobject.embedSWF("/flash/global/McMensHeader.swf", "flash_jax_head", "1024", "200", "9.0.0","/expressInstall.swf", flashvars, params, attributes);

	params.flashvars = 'dir=E';
	swfobject.embedSWF("/flash/global/pipe2.swf", "flash_jax_pipe_plume_two", "80", "80", "9.0.0","/expressInstall.swf", flashvars, params, attributes);

	params.flashvars = 'dir=S';
	swfobject.embedSWF("/flash/global/pipe.swf", "flash_jax_pipe_plume_three", "80", "80", "9.0.0","/expressInstall.swf", flashvars, params, attributes);

	params.flashvars = '';
	swfobject.embedSWF("/flash/global/pipe.swf", "flash_jax_pipe_plume", "80", "80", "9.0.0","/expressInstall.swf", flashvars, params, attributes);
	
	swfobject.embedSWF("/flash/global/Footer.swf", "flash_jax_foot", "1400", "360", "9.0.0","/expressInstall.swf", flashvars, params, attributes);
	
	if(jQuery('body').hasClass('day'))
		var timeofday = 'd';
	else
		var timeofday = 'n';
	
	params.flashvars = 'dir=E&time=' + timeofday
	swfobject.embedSWF("/flash/global/lightSconce3_DC.swf", "flash_jax_sconce_right", "100", "100", "9.0.0","/expressInstall.swf", flashvars, params, attributes);
	
	params.flashvars = 'dir=W&time=' + timeofday;
	swfobject.embedSWF("/flash/global/lightSconce3_DC.swf", "flash_jax_sconce_left", "100", "100", "9.0.0","/expressInstall.swf", flashvars, params, attributes);
	
	
}

function ToolTip(element, tipper, tip_name, replace)  {
	var self = this;
	self.root = jQuery('#jax_content');
	self.root.append(element);
	self.root.children('.toolTip:last').addClass(tip_name);
	var toolTip = self.root.find('.' + tip_name);
	if (replace)
		toolTip.children('.tip_cont').html(tip_name.replace(/_/g, ' '));
	toolTip.show();
	toolTip.css({
		top: (tipper.offset().top - toolTip.outerHeight() - 30),
		left: (tipper.offset().left - (toolTip.outerWidth() * .4) - 30),
		height: toolTip.children('.tip_cont').height(),
		width: toolTip.children('.tip_cont').outerWidth() + 10
	});
	toolTip.children('.tip_cont').css('width', toolTip.width()-6);
	toolTip.hide();
	tipper.hover(
		function()  {
			toolTip.show();
		},
		function()  {
			toolTip.hide();
		}
	);

}

function Emailer(element)  {
	var self = this;
	this.root = element;
	this.email_tip = null;
	jQuery.ajax({
		url:"/email_tooltip",
		success: function(html)  {
			self.email_tip = new ToolTip(html, self.root, 'email', false);
		}
	});
	
	this.root.click(function() {
		jQuery.ajax({
			url: "/contact/refer",
			async: false,
			success: function(html) {
				jQuery('#container').after(html);
				self.ajaxed = jQuery('#container').siblings('.refer');
				self.ajaxed.dialog({
					title: "Email a Friend",
					modal: true,
					height: 534,
					width: 475,
					buttons: {
						send: function()  {
							var formData = self.ajaxed.find('form').serialize();
							self.ajaxed.find('#errorExplanation').remove();
							jQuery.ajax({
								url: "/contact/refer",
								type: "POST",
								data: formData,
								async: false,
								success: function(html) {
									var tempHtml = jQuery(html).find('#errorExplanation');
									if (tempHtml.hasClass('errorExplanation')) {
										self.ajaxed.find('h2').after(tempHtml);
									}
									else  {
										self.ajaxed.html("<h3>Success</h3>");
										self.ajaxed.fadeOut(500, function() {self.ajaxed.dialog('close')});
									}
								}
							});
							//self.ajaxed.dialog('close');
						}	
					},
					close: function()  {
						self.ajaxed.dialog('destory').remove();
					}
				});
			}
		});
	});
}

function ProdList(element)  {
	var self = this;
	this.root = element;
	this.quickView = this.root.find('.quick_view').show();

	for(var i = 0; i < this.quickView.length; i++)  {
		this.quickView[i] = new ProdQuick(jQuery(this.quickView[i]));
	}
	this.root.find('.quick_view').hide();
	this.lineBreakFix = this.root.find('.title h3');
	for(var i = 0; i < this.lineBreakFix.length; i++)  {
		var tempFix = jQuery(this.lineBreakFix[i]).html()
		tempFix = tempFix.replace(/T-shirt/, '<i> T-shirt </i>');
		jQuery(this.lineBreakFix[i]).html(tempFix);
	}

}

function ProdQuick(element)  {
	var self = this;
	this.root = element;
	this.url = this.root.attr('name');
	this.root.parent().hover(
		function()  {
      		this.t = setTimeout(function()  {
				self.root.fadeIn(200);
				self.root.siblings().fadeTo(200, .6);
			}, 700);
		},
		function()  {
			clearTimeout(this.t);
			self.root.fadeOut(200);
			self.root.siblings().fadeTo(200, 1);
		}
	);
	this.clicked = false;
	this.root.click(function()  {
		if (!self.clicked)
			self.clicked = true;
			jQuery.ajax({
				type: "GET",
				url: self.url,
				async: false,
				success: function(html)  {
					self.quickContent = jQuery(html);
					self.quickContent.dialog({
						height: 650,
						width: 600,
						resizable: true,
						modal: true,
						close: function()  {
							self.clicked = false;
							jQuery(this).dialog('destroy').remove();
						}
					});
					new productDetail(self.quickContent);
					new ProductChooser(self.quickContent.find('.product_info')[0], function() { 
						if (!(jQuery('#qv-product-added')[0]))
							jQuery(document.body).append('<div id="qv-product-added"></div>');
						jQuery("#qv-product-added").html("The product was added to your cart.")
						self.quickContent.dialog('close'); 
						jQuery("#qv-product-added").dialog({
							buttons: { 
								"Continue Shopping":
									function() { jQuery("#qv-product-added").dialog("close"); },
								"View Cart":
									function() { window.location = "/cart"; }
							}
						});
					});
				}
			});
	});	
}

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/number/fmt-money [rev. #2]

Number.prototype.formatMoney = function(c, d, t){
    var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "",
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t)
    + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}; 

function Tabb(element)  {
	var self = this;
	this.root = element;
	jQuery('#tabber li:first').addClass("active");
	jQuery('#tabber li').click(function (e) {
		var tab = jQuery(this).attr("id");
		jQuery('#tabber li.active').removeClass("active");
		jQuery(this).toggleClass("active");
		tab = tab.slice(4, tab.length);
		var contents = jQuery("div.tabedContent");
		contents.hide();
		jQuery("#tab-content-" + tab).show();
		return false;
	});
}
function Navi(element)  {
	var self = this;
	this.root = element;
	this.root.find('ul').show();
	this.root.find('div').slideUp(1);
	this.naviElem = this.root.children('li');
	if (this.naviElem.length != 0)  
		for (var i = 0; i < this.naviElem.length; i++) 
			this.naviElem[i] = new SubNavigation(jQuery(this.naviElem[i]), i);
}

function NaviNode(element)  {
	var self = this;
	this.root = element;
	this.subUL = this.root.children('ul');
	this.subLI = this.subUL.children('li');
	this.naviCall = this.root.find('div');
	this.root.hover(
      function () {
	  	//self.subUL.show(.1, function() {self.naviCall.show(.1);});
	  	self.subUL.show();
	  	jQuery(this).children('a').addClass("selected");

	  }, 
      function () {
	  	jQuery(this).children('a').removeClass("selected");
	  	self.subUL.hide();
	  	//self.subUL.hide(.1, function() {self.naviCall.hide(1);});
	  }
    );
}

function SubNavigation(element, index)  {
	NaviNode.call(this, element);

	this.subUL.css('top', this.root.outerHeight());
/*this.subUL.css('width', '1000px');
	for (var i = 0; i < this.subLI.length; i++)  
		jQuery(this.subLI[i]).children('a').css('width', jQuery(this.subLI[i]).children('a').outerWidth());

	if (this.subLI.length > 6) {
		var numInColumn = Math.floor(this.subLI.length/2) + 1;
		this.subUL.html('<li><ul id="navColumnLeft"> </ul> </li><li><ul id="navColumnRight"> </ul> </li>');
		var cL = this.subUL.find('#navColumnLeft');
		var cR = this.subUL.find('#navColumnRight');
		for (var i = 0; i < this.subLI.length; i++)  
			if (i < numInColumn)
				cL.append(this.subLI[i]);
			else 
				cR.append(this.subLI[i]);
		this.subUL.css('width', cL.outerWidth() + cR.outerWidth() + 10);
	}
	else
	this.subUL.css('width', 'auto');
*/	

	this.subUL.hide();
}

function ProductViewer() {
  $('.product_viewer dd img').
    click(function(e) {
	  if ($('#tShirtViewer').length != 0) {
	  	$('#tShirtViewer').hide().css('visibility', 'hidden');
	  	$('#product_photo').show();
	  }
      $(this).siblings().
          removeClass('currentPhoto').
        end().
          addClass('currentPhoto');
      $("#product_photo").
        attr('src', $(this).attr('src').replace('thumbnail.jpg', 'medium.jpg'));
    }).
      filter(':first').
        addClass('currentPhoto');
    
}

function SelectProductInViewer(id) {
  if (id == "") { return; }
  var img = $('.product_viewer dd img#variation_image_' + id);
    img.siblings().
      removeClass('currentPhoto').
    end().
      addClass('currentPhoto');
      if (img.siblings().length > 0);
    		$("#product_photo").attr('src', $(img).attr('src').replace('thumbnail.jpg', 'medium.jpg'));
}

$(function() {
  $('input[value=Continue Shopping]').click(function() { window.history.back(); return false; });
});

// When a country or region is selected, updates the state/provinces selector
function countryAndStateSelector() {
  $('.select-country :input').change(function() {
      var country_id = $(this).val();
      var state_selector = $('.select-state select')
      $.getJSON('/countries/'+country_id+'/states.json', function(states) {
        state_selector.html('<option>Choose a state or province</option>');
        for (i = 0; i < states.length; i++) {
          states[i] = eval('(' + states[i] + ')');
          state_selector.append('<option value="'+states[i].code+'">' + states[i]['name'] + '</option>');
        }
      });
  });
}

var submit_code = function() {
    window.location = "/cart/claim?code=" + $('#code')[0].value;
};

var submit_order_total_modification = function() {
    window.location = "/cart/total?amount=" + $('#adjusted_total')[0].value;
};

