if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)) {
	var viewportmeta = document.querySelectorAll('meta[name="viewport"]')[0];
	if (viewportmeta) {
		viewportmeta.content = 'width=device-width, minimum-scale=1.0, maximum-scale=1.0';
		document.body.addEventListener('gesturestart', function() {
			viewportmeta.content = 'width=device-width, minimum-scale=0.25, maximum-scale=1.6';
		}, false);
	}
}
$(document).ready(function(){
	if(window.location.hash) {
		scrollName = window.location.hash.substr(1);
		anchor = '';
		anchor = $("[name='"+scrollName+"']");
		$('html, body').animate({
			scrollTop: anchor.offset().top - 200
		}, 1000, "swing", function(){
			anchor.children('img').css('box-shadow','0px 0px 10px #871E38');
		});
	}
	
	/*==========================================
	EXPAND FUNCTIONALITY OF SUBMIT HERE TO SAVE IN URLBAR
	==========================================*/
	
	$('img.press').parent('a').css({
		'height':'120px',
		'overflow':'hidden'
	});
	
	
	$("[placeholder]").focus(function() {
			var input = $(this);
			if (input.val() == input.attr("placeholder")) {
				input.val("");
				input.removeClass("placeholder");
				}
		}).blur(function() {
			var input = $(this);
			if (input.val() == "" || input.val() == input.attr("placeholder")) {
				input.addClass("'placeholder'");
				input.val(input.attr("placeholder"));
			}
	}).blur();
	$(window).load(function(){
		if (!$.browser.msie){
			if($('div[role="masonry"]')[0]){
				$('div[role="masonry"]').isotope({
					sortBy : 'random',
					masonry: {
						rowHeight: 170,
						columnWidth: 245
					}
				});
			}
		}else{
			$('.brick').each(function(){
				brickNumber = $('[role="masonry"] .brick').index(this);
				$(this).attr('rel',brickNumber);				
			});
			$('.brick[rel="6"],.brick[rel="7"]').insertAfter('.brick[rel="1"]');
			$('.brick[rel="2"]').insertAfter('.brick[rel="3"]');
			if($('div[role="masonry"]')[0]){
				$('div[role="masonry"]').isotope({
					masonry: {
						rowHeight: 170,
						columnWidth: 245
					}
				});
			}
		}
		shuffle = function(){
			//alert($('div[role="masonry"]').height());
			if($('div[role="masonry"]').width()>998){
				maxHeight = 680;
			}else{
				maxHeight = 850;
			}	
			if($('div[role="masonry"]').height()>maxHeight){
				$('div[role="masonry"]').isotope('shuffle');
				shuffle();
			}//850
		}
		if (!$.browser.msie){
			shuffle();
		}
	});
	
	$('div[role="masonry"] .description').css('display','block');
	$('div[role="masonry"] .description').each(function(){
		$(this).animate({
			'bottom' : -$(this).height() -20
		}, { queue: false, duration: 300 });
	});
	$('div[role="masonry"] .brick').hover(
		function(){
			$(this).children('.description').animate({
				'bottom' :0
			}, { queue: false, duration: 300 });
		},function(){
			$(this).children('.description').animate({
				'bottom' : -$(this).children('.description').height() -20
			}, { queue: false, duration: 300 });
		}
	);
	
	
	$('[role="categoryList"] a[href$="jpg"], [role="categoryList"] a[href$="JPG"]').fancybox();
	/*$('[role="categoryList"] a[href$="jpg"], [role="categoryList"] a[href$="JPG"]').fancybox({
		'onStart': function(link,index){
			$('[role="categoryList"] a img').css('box-shadow','none');
			$(link[index]).children('img').css('box-shadow','0px 0px 7px #871E38');
			window.location.hash = $(link[index]).attr('name');
			$('html, body').animate({
				scrollTop: $(link[index]).offset().top - 200
			}, 1000, "swing");
		}
	});
	$('[role="categoryList"] a').click(function() {
		if(!$('[role="categoryList"] a[href$="jpg"]')[0]){
			$('[role="categoryList"] a img').css('box-shadow','none');
			$(this).children('img').css('box-shadow','0px 0px 7px #871E38');
			$('html, body').animate({
				scrollTop: $(this).offset().top - 200
			}, 1000, "swing");
		}
	});*/
	help = true;
	
	$('#needhelp h4').click(function(){
		$('#needhelp').animate({
			'width':'250px'
		})
		 help = true;
		 
	});
	$('#needhelp').mouseleave(function(){
		if(help){
			$('#needhelp').animate({
				'width':'48px'
			});
			help = false;
		}
	});	
	$('#search input[type="text"], #needhelpForm input[type="text"]').wrap('<span class="brackets"></span>');
	//$('div[role="sidebar"]').width($('div.content').innerWidth()-$('div[role="main"]').outerWidth());
	
	$('#startnow, #buynow').fancybox({
		'type'				: 'iframe',
		'autoDimensions'	: false,
		'width'				: 390,
		'height'			: 640,
		'padding'			: 20,
		'autoScale'			: false,
		'autoDimensions'	: false,
		'scrolling'			: 'no'
	});
	
	
	$('.banner, .productListing h5').each(function(){
		//alert($(this).css('font-size'));
		$(this).css({
			'border-bottom-width': Math.round((parseFloat($(this).css('font-size'))+11)/2),
			'border-right-width': Math.round((parseFloat($(this).css('font-size'))+11)/2),
			'border-top-width': Math.round((parseFloat($(this).css('font-size'))+11)/2)
		});
	});
	
	$.fn.setAllToMaxHeight = function(){
		return this.css('min-height',( Math.max.apply(this, $.map( this , function(e){ return $(e).height() }) ) ));
	}	
	
	
	$('.information section .content').hide();
	$('.information section h3').not('.social h3').click(function(){
		$(this).siblings('.content').slideToggle();
	}).toggle(function(){
		$(this).children('.toggle').css('background-position','0 0').end().children('.tooltip').html('Hide').end();
	},function(){
		$(this).children('.toggle').css('background-position','0 -7px').end().children('.tooltip').html('Show');
	}).css('cursor','pointer').hover(
		function(){
			$(this).dequeue().children('.tooltip').fadeIn(100);
		},
		function(){
			$(this).dequeue().children('.tooltip').fadeOut(100);
	}).append('<span class="toggle"></span><span class="tooltip">Show</span>').dequeue();
	
	$('.information').mousemove(function(e){
        $('.tooltip').css({
            top: (e.pageY - 20) ,
            left: (e.pageX + 15)
        });
    });
	
	$('.thumbnails a').click(function(){
		newImage = $(this).attr('href');		
		$('html, body').animate({
			scrollTop: $('#product').offset().top
		}, 500, "swing");
		$('.mainImage img').attr('src',newImage);
		return false
	});
	
	
	
	$('#contactUsForm').validate({
		invalidHandler: function(form, validator) {
		var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
				? 'You missed 1 field. It has been highlighted'
				: 'You missed ' + errors + ' fields. They have been highlighted';
				$("div.error span").html(message);
				$("div.error").show();
			} else {
				$("div.error").hide();
			}
		},
		messages: {
			state: 'Required',
			postalcode: 'Required'
		}
	});
	
	$('#needhelpForm').validate({
		messages: {
			name: '',
			phone: ''
		}
	});
	$('#needhelpForm').ajaxForm({
		target:"#needhelpForm",     //set response to go into hidden div    
		beforeSubmit:function(){  //before sending submit, give user notification...
			$("#needhelpForm").html('<h3 class="center">...Sending...</h3>');
		},
		success:function(rtn){
			$("#needhelpForm").html('<h3 class="center">Thank you!</h3><p>We will get back to you as soon as we can.</p>');
			//console.log(rtn)
		}
	});
	
	//LIST ITEM EXPAD FOR TAGS
	$('<li class="more">Show All</li>').insertAfter('.tag_list li:eq(9)');
	$('.tag_list li:gt(10)').hide();
	$('li.more').click(function(){
		$('.tag_list li:gt(10)').show();
		$(this).fadeOut();
	});
	
	//$('.tag_list li :checked').parent('li').insertBefore('.tag_list li:eq(0)');
	
	
	$('select[name="orderby"]').change(function(e){
		if($(this).val()=="title"){
			$('select[name="sortby"]').val('asc');
		} else {
			$('select[name="sortby"]').val('desc');
		}
	});
	
	$('#searchbar').validate({
		submitHandler: function(form) {
			$('.productList').empty().html('<h3 class="center">...Loading Products...<br /><img src="/images/loading.png" /></h3>');
			$('input[name="order"]').val($('select[name="orderby"]').val()+"+"+$('select[name="sortby"]').val());
			$.ajax({
				url: $(form).attr("action"),
				type: "POST",
				data: $(form).serialize(),
				success: function(response) {
					$('.productList').html(response);
				},
				error: function() {
				  //Add an oops message
				  //Show it and then configure a timeout to delete it
				  alert("error");
				}
			});
		}
	});
	
	$('#searchbar input, #searchbar select').change(function(){
		$(this).closest('form').submit();
			//window.location.hash = $("#searchbar").serialize();
			//alert(getHashByName('category[]'));
	});
	//$('#searchbar input[type="checkbox"]:checked').removeAttr('checked');
	
	
	/*if(window.location.hash) {
		decodedURI = decodeURIComponent(window.location.hash);
		//alert(decodedURI);
		loadSerializedData('searchbar', decodedURI);
	}
	
	function loadSerializedData(formId, data){
		var tmp = data.split('&')
		var dataObj = {};
	
		// Bust apart the serialized data string into an obj
		for (var i = 0; i < tmp.length; i++){
			var keyValPair = tmp[i].split('=');
			dataObj[keyValPair[0]] = keyValPair[1];
		}
	
		// Loop thru form and assign each HTML tag the appropriate value
		$('#' + formId + ' :input').each(function(index, element) {
			if (dataObj[$(this).attr('name')]){
				$(this).val(dataObj[$(this).attr('name')]);
			}
		});
	}*/

	
	
	function getHashByName(name){
		name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
		var regexS = "[\\#&]" + name + "=([^&#]*)";
		var regex = new RegExp(regexS);
		var results = regex.exec(window.location.hash);
		if(results == null){
			return "";
		}else{
			return decodeURIComponent(results[1].replace(/\+/g, " "));
		}
	}
	
	function getParameterByName(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, " "));
		}
	}
	

	//alert(getParameterByName('category'));
	
	/*==========================================
	EXPAND FUNCTIONALITY OF SUBMIT HERE TO SAVE IN URLBAR
	==========================================*/
	
	if('' != getParameterByName('category')){
		newCat = getParameterByName('category');
		//alert(newCat)
		$('#searchbar input[type="radio"]').removeAttr('checked')
		$('#searchbar input[value="'+newCat+'"]').attr('checked','checked');
	}
	
	if($('.productList')[0]){
		$('#searchbar').submit();
	}
	
	$('.productList .paginate a').live('click', function(ev) {
		// Stop regular handling of "click" in most non-IE browsers
		$("html, body").scrollTop(0);
		ev.preventDefault();
		ev.stopPropagation();
		$('.productList').empty().html('<h3 class="center">...Loading Products...<br /><img src="/images/loading.png" /></h3>');
		// Load the new content into the div (same code you had)
		
		$.ajax({
			url: $(this).attr('href'),
			type: "POST",
			success: function(response) {
				$('.productList').html(response);
			},
			error: function() {
			  //Add an oops message
			  //Show it and then configure a timeout to delete it
			  alert("error");
			}
		});
		// Stop regular handling of "click" in IE (and some others)
		return false;
	});

	
	$('.collapse a').click(function(){
		$(this).siblings('ul').slideToggle();
	}).toggle(function(){
		$(this).children('.toggle').css('background-position','0 -7px').end().children('.tooltip').html('Show').end();
	},function(){
		$(this).children('.toggle').css('background-position','0 0').end().children('.tooltip').html('Hide');
	}).css('cursor','pointer').hover(
		function(){
			$(this).dequeue().children('.tooltip').fadeIn(100);
		},
		function(){
			$(this).dequeue().children('.tooltip').fadeOut(100);
	}).append('<span class="toggle"></span><span class="tooltip">HIde</span>').dequeue();
	
	$('#searchbar').mousemove(function(e){
        $('.tooltip').css({
            top: (e.pageY - 20) ,
            left: (e.pageX + 15)
        });
    });



	$('article img').each(function(e){	
		if($(this).css('float') == 'right'){
			$(this).addClass('right');
		}else if($(this).css('float') == 'left'){
			$(this).addClass('left');
		}
	});

	/*equalHeight = function(){
		$('.gallery, .information').setAllToMaxHeight();
	}
	equalHeight();
	
	$(window).bind("resize", equalHeight);*/
	
	/*$('.banner:before').each(function(){
		$(this).css({
			'font-size':'inherit',
			'border-bottom-width': Math.round((parseFloat($(this).css('font-size'))+10)/2),
			'border-right-width': Math.round((parseFloat($(this).css('font-size'))+10)/2),
			'border-top-width': Math.round((parseFloat($(this).css('font-size'))+10)/2),
			'right': (parseFloat($(this).css('font-size'))+10)/2-1,
			'top': (parseFloat($(this).css('font-size'))+10)/2+1
		});
	});
	$('.banner:after').each(function(){
		$(this).css({
			'font-size':'inherit',
			'border-bottom-width': Math.round((parseFloat($(this).css('font-size'))+10)/2),
			'border-right-width': Math.round((parseFloat($(this).css('font-size'))+10)/2),
			'border-top-width': Math.round((parseFloat($(this).css('font-size'))+10)/2),
			'right': (parseFloat($(this).css('font-size'))+10)/2-2,
			'top': (parseFloat($(this).css('font-size'))+10)/2+2
		});
	});*/
	
	$('.picturetilt').each(function (){
		randomNum = Math.random()*4-2;
		$(this).css({
			'-webkit-transform': 'rotate(' + randomNum + 'deg)',
			'-moz-transform': 'rotate(' + randomNum + 'deg)',
			'-ms-transform': 'rotate(' + randomNum + 'deg)',
			'-o-transform': 'rotate(' + randomNum + 'deg)',
			'transform': 'rotate(' + randomNum + 'deg)',
			'zoom': 1
		});
	});
});
