jQuery(document).ready(function($) {
    
    /* PAGE */
	
	var curtitle = document.title;
	var phone_ui = (($("body").hasClass("is_mobile")) ? true : false);
	var screen_width = $(window).width();
	var mq_screen_width = 1280;
	var show_full = false;
	var background_url = '';
	
	// initial load
	if(screen_width > mq_screen_width || !phone_ui) showBGImage();	
	
	// on resize
	$(window).resize(function(){
		if(phone_ui){
			var new_screen_width = $(window).width();
			if(new_screen_width > mq_screen_width) {
				showBGImage();
				screen_width = new_screen_width;
			}else{
				$('html').css({'background':'#000'});
				show_full = false;
				fit_section_buttons();
			}
		}		
	});
	
	// background image
	function showBGImage(){
		show_full = true;
		var post_id = $('#nav-inventory-post-id').val();
		var root = $('#nav-inventory-root-folder').val();
		if(background_url == ''){
			if(root != '' && root != undefined){
		    	$.post(	root+"ajax.php", 
					{op:'getbgimage', post_id:post_id},
					function(html){
						if(html != ''){
							$('html').css({'background': 'url(\''+html+'\')', 'background-position': 'center 36px', 'background-repeat': 'no-repeat', 'background-color' : '#040402' });
							background_url = html;
						}else{
							$('html').css({'background': 'url(/wp-content/themes/chimera/images/interface/bg.jpg)', 'background-position': 'center 36px', 'background-repeat': 'no-repeat', 'background-color' : '#040402' });
						}
					}
		    	);
			}else{
				$('html').css({'background': 'url(/wp-content/themes/chimera/images/interface/bg.jpg)', 'background-position': 'center 36px', 'background-repeat': 'no-repeat', 'background-color' : '#040402' });
			}
		}else{
			$('html').css({'background': 'url(\''+background_url+'\')', 'background-position': 'center 36px', 'background-repeat': 'no-repeat', 'background-color' : '#040402' });
		}
	}
	
	var left = (parseInt($('.nav-inventory-active').css('width')) - 30) / 2;
	$('.nav-inventory-active-arrow').css('left', left+'px');
    
	/* PRODUCT DETAILS */
	
	// fit section buttons in nav bar width (mobi)
	function fit_section_buttons(){
		var num_sections = $("#nav-inventory-sections-mobi .nav-inventory-sections-button").length;
		//alert(num_sections);
		if(num_sections > 1) {
			var phone_section_width = 100/(num_sections)+"%";
			$("#nav-inventory-sections-mobi .nav-inventory-sections-button").each(function(){
				$(this).css("width", phone_section_width);
			});
		}else {
			var phone_section_width = "20%";
		}
	}
	if(phone_ui && !show_full) fit_section_buttons();
	
	// show/hide active section div based on active button
	$("li.nav-inventory-sections-button").each(function(){
		var rel = $(this).find('a').attr('rel');
		if($(this).hasClass("nav-inventory-sections-active")){
			$("#nav-inventory-"+rel+"-wrapper").show();
			$("#nav-inventory-sections").attr("rel", rel);
			$("#nav-inventory-sections-mobi").attr("rel", rel);
			updateSEOInfo(rel);
		}else{
			$("#nav-inventory-"+rel+"-wrapper").hide();
		}
	});
	
	// change active section button
	$(".nav-inventory-sections-button a").click(function(){
		var cur = $(this);
		var ul = cur.closest('ul');
		var last = ul.attr("rel");
		var rel = cur.attr("rel");
		if(last != undefined){
			$("#nav-inventory-"+last+"-wrapper").hide();
			ul.find(".nav-inventory-sections-active").removeClass("nav-inventory-sections-active");
		}
		
		cur.parent().addClass("nav-inventory-sections-active");
		$("#nav-inventory-"+rel+"-wrapper").show();
		ul.attr("rel", rel);
		
		updateSEOInfo(rel);
	});
	
	// click on img thumb. change main image
    $(".navstore-prod-thms-img").click(function(){
    	var img = $(this).closest('li').find('.navstore-prod-thm-large');
    	$("#mainpicDiv img").attr('src', img.attr('src'));
    	var img = $(this).closest('li').find('.navstore-prod-thm-med');
    	$("#navstore-prod-mainpic-med").attr('src', img.attr('src'));
    });
    
    // zoom in
    $('#nav-inventory-thumbs li a').click(function(e){
    	e.preventDefault();
    	var thm = $(this);
    	var rel = thm.attr('rel');
    	var imgatts = rel.split('|');
    	var width = parseInt(imgatts[0]);
    	var height = parseInt(imgatts[1]);
    	if(width > 691) {
    		var ratio = height / width;
    		width = 691;
    		height = 691 * ratio;
    	}
    	
    	$('#nav-inventory-main-photo-img').attr('src', imgatts[2]);
    	$('#nav-inventory-zoom-photo-img').attr('src', imgatts[4]);
    	$('#nav-inventory-zoom-photo-img').attr('rel', imgatts[5]);
    	$('#nav-inventory-main-caption span').html(imgatts[3]);
    	$('#nav-inventory-thumbs li').each(function(){
    		$(this).removeClass('nav-inventory-thumbs-active');
    	});
    	thm.parent().addClass('nav-inventory-thumbs-active');
    });
    
    // update seo items
    function updateSEOInfo(rel){
    	if(!phone_ui || show_full){
	    	var title = $('#nav-inventory-'+rel+'-seo-title').val();
	    	var descr = $('#nav-inventory-'+rel+'-seo-descr').val();
	    	var keywd = $('#nav-inventory-'+rel+'-seo-keywd').val();
	    	if(title != undefined && title != ''){
	    		document.title = curtitle + ' | ' + title;
	    	}else{
	    		document.title = curtitle;
	    	}
	    	if(descr != undefined && descr != ''){
	    		$('meta[name=description]').attr('content', descr);
	    	}
	    	if(keywd != undefined && keywd != ''){
	    		$('meta[name=keywords]').attr('content', keywd);
	    	}
    	}
    }
    
	/* POPUP JS */
    
	$("#bgPopup").data("state",0);  
	$("#Popup").appendTo('html');
	var maxthumbsshown = 13;			// will show maxthumbsshown / 2 on either side of active thumb
    
	if(!phone_ui || show_full) {
	    $('#nav-inventory-main-photo-img, #nav-inventory-view-more-photos').click(function(){
			var popupImg = $('#nav-inventory-zoom-photo-img');
			$('#Popup').css({
					'background-image':'url("' + popupImg.attr('src') + '")', 
					'background-repeat':'no-repeat',
					'background-position':'center center'
				});
			centerPopup();  
			loadPopup();  
			addZoomThumbs();
	    	return false;
	    });
	}
	
    $(document).delegate('.zoomThumbItem', 'click', function(){
    	var elem = $(this);
    	selectThumb(elem.find('.zoomThumb'));
    });
    
    $(document).delegate('#popupLeftButton', 'click', function(){
    	$(this).blur();
    	slideThumbs('left');
    });
    
    $(document).delegate('#popupRightButton', 'click', function(){
    	$(this).blur();
    	slideThumbs('right');
    });
    
    $('#bgPopup').click(function(){
    	disablePopup(); 
    });
    
	$("#popupClose").click(function(){  
		disablePopup();  
	});  
	
	$(document).keypress(function(e){  
		if(e.keyCode==27) {  
			disablePopup();  
		}  
	}); 
	
	function loadPopup(){  
		//loads popup only if it is disabled  
		if($("#bgPopup").data("state")==0){  
			$("#bgPopup").css({  
				"opacity": "0.7"  
			});  
			$("#bgPopup").fadeIn("medium");  
			$("#Popup").fadeIn("medium");  
			$("#bgPopup").data("state",1);  
		}  
	}  
	  
	function disablePopup(){  
		if ($("#bgPopup").data("state")==1){  
			$("#bgPopup").fadeOut("medium");  
			$("#Popup").fadeOut("medium");  
			$("#bgPopup").data("state",0);  
		}  
	}  
	  
	function centerPopup(){  
		var winw = $(window).width();  
		var winh = $(window).height();  
		var popw = $('#Popup').width();  
		var poph = $('#Popup').height(); 
		$("#Popup").css({  
			"position" : "absolute",  
			"top" : winh/2-poph/2,  
			"left" : winw/2-popw/2  
		});

		//IE6  
		$("#bgPopup").css({  
			"height": 2000  
		});  
	} 
	
	function addZoomThumbs(){
		var post_id = $('#nav-inventory-post-id').val();
		var root = $('#nav-inventory-root-folder').val();
		var cur_zoom_index = $('#nav-inventory-zoom-photo-img').attr('rel');
    	$.post(	root+"ajax.php", 
			{op:'getzoomthumbs', post_id:post_id, cur_zoom_index:cur_zoom_index, maxshown:maxthumbsshown},
			function(html){
				if(html != ''){
					$('#popupThumbs').remove();
					$('#Popup').append(html);
				}else{
				}
			}
    	);
	}
	
	function selectThumb(elem){
    	var rel = elem.attr('rel');
    	var rel_split = rel.split('|');
		$('#Popup').css({
			'background-image':'url("' + rel_split[0] + '")', 
			'background-repeat':'no-repeat',
			'background-position':'center center'
		});  
		$('.zoomThumb').each(function(){
			if($(this).parent().hasClass('activeThumb')){
				$(this).parent().removeClass('activeThumb').animate({
				    'margin-bottom':'0px'
				}, 200);
			}
		});
		elem.parent().addClass('activeThumb').css({'margin-bottom':'10px'});
	}
	
	function slideThumbs(dir){
		var maxthumbsshownperside = Math.floor(maxthumbsshown / 2);
		var curthumb = $('.activeThumb');
		var curthumbindex = parseInt(curthumb.attr('rel'));
		var lastthumbindex = $('.zoomThumbItem').length;
		var incr = ((dir == 'left') ? -1 : 1);
		var nextthumbindex = curthumbindex + incr;
		
		if (nextthumbindex >= 1 && nextthumbindex <= lastthumbindex){
			var onthumbindex;
			if(nextthumbindex <= maxthumbsshownperside){
				// left
				var firstthumbshown = 0;
				var lastthumbshown = firstthumbshown + maxthumbsshown + 1;
			}else if(nextthumbindex < lastthumbindex - maxthumbsshownperside){
				// middle
				var firstthumbshown = nextthumbindex - maxthumbsshownperside;
				var lastthumbshown = firstthumbshown + maxthumbsshown;
			}else{
				// right
				var firstthumbshown = lastthumbindex - maxthumbsshown;
				var lastthumbshown = firstthumbshown + maxthumbsshown;
			}
			$('#popupThumbs li').each(function(){
				onthumbindex = $(this).attr('rel');
				if((onthumbindex < firstthumbshown) || (onthumbindex > lastthumbshown)){
					$(this).addClass('hideThumb');
				}else{
					$(this).removeClass('hideThumb');
				}
			});
			var elem = $('#zoomThumb'+nextthumbindex);
			selectThumb(elem);
		}
	}
	
	/* OTHER */
    
    function validateDate(dt_y, dt_m, dt_type){
    	var dt = new Date();
    	var y = dt.getFullYear();
    	var m = dt.getMonth() + 1;
    	var curdt_calc = y * 100 + m;
    	var dt_calc = parseInt(dt_y) * 100 + parseInt(dt_m);
    	
    	if(dt_calc < curdt_calc){
    		alert(dt_type+' has expired.');
    		return false;
    	}else{
    		return true;
    	}
    }

    // Add a class to body tag when browser window is less than 1024px size//){
	$(window).resize(function(){
		if ($(window).width() < 1024){
			$('body').addClass('too-narrow');
		} else {
			$('body').removeClass('too-narrow');
		}
	});

	$('#username, #password').focus(function() {
		if($(this).val() == 'Username')
			$(this).val('');
			
		// If password, convert to password field
		if($(this).attr('id') == 'password') {
			$('#password').hide();
			$('#realpassword').show();
			$('#realpassword').focus();
		}			
	});
	
	$('#username, #realpassword').blur(function() {	
		var replace;
		replace = $(this).attr('id');
								
		if($(this).val() == '' && $(this).attr('id') == 'username')
			$(this).val(replace.charAt(0).toUpperCase() + replace.slice(1));
			
		if($(this).attr('id') == 'realpassword' && $(this).val() == '') {
			$('#realpassword').hide();
			$('#password').show();
		}
	});	
});

function trimstring(str){
	if (str.trim)
		return str.trim();
	else
		return str.replace(/(^\s*)|(\s*$)/g, ""); //find and remove spaces from left and right hand side of string
}

