/*!
* Fruitful Deliveries
* http://www.fruitfuljam.com
* Copyright 2011, Andy Perlitch
*/
/*
 * jQuery autoResize (textarea auto-resizer)
 * @copyright James Padolsey http://james.padolsey.com
 * @version 1.04
 */

(function(d){var b="ar"+ +new Date,e=c.defaults={onResize:function(){},onBeforeResize:function(){return 123},onAfterResize:function(){return 555},animate:{duration:200,complete:function(){}},extraSpace:50,minHeight:"original",maxHeight:500,minWidth:"original",maxWidth:500};c.cloneCSSProperties=["lineHeight","textDecoration","letterSpacing","fontSize","fontFamily","fontStyle","fontWeight","textTransform","textAlign","direction","wordSpacing","fontSizeAdjust","paddingTop","paddingLeft","paddingBottom","paddingRight","width"];c.cloneCSSValues={position:"absolute",top:-9999,left:-9999,opacity:0,overflow:"hidden"};c.resizableFilterSelector=["textarea:not(textarea."+b+")","input:not(input[type])","input[type=text]","input[type=password]","input[type=email]","input[type=url]"].join(",");c.AutoResizer=a;d.fn.autoResize=c;function c(f){this.filter(c.resizableFilterSelector).each(function(){new a(d(this),f)});return this}function a(g,f){if(g.data("AutoResizer")){g.data("AutoResizer").destroy()}f=this.config=d.extend({},c.defaults,f);this.el=g;this.nodeName=g[0].nodeName.toLowerCase();this.originalHeight=g.height();this.previousScrollTop=null;this.value=g.val();if(f.maxWidth==="original"){f.maxWidth=g.width()}if(f.minWidth==="original"){f.minWidth=g.width()}if(f.maxHeight==="original"){f.maxHeight=g.height()}if(f.minHeight==="original"){f.minHeight=g.height()}if(this.nodeName==="textarea"){g.css({resize:"none",overflowY:"hidden"})}g.data("AutoResizer",this);f.animate.complete=(function(h){return function(){f.onAfterResize.call(g);return h.apply(this,arguments)}}(f.animate.complete));this.bind()}a.prototype={bind:function(){var f=d.proxy(function(){this.check();return true},this);this.unbind();this.el.bind("keyup.autoResize",f).bind("change.autoResize",f).bind("paste.autoResize",function(){setTimeout(function(){f()},0)});if(!this.el.is(":hidden")){this.check(null,true)}},unbind:function(){this.el.unbind(".autoResize")},createClone:function(){var f=this.el,g=this.nodeName==="textarea"?f.clone():d("<span/>");this.clone=g;d.each(c.cloneCSSProperties,function(h,j){g[0].style[j]=f.css(j)});g.removeAttr("name").removeAttr("id").addClass(b).attr("tabIndex",-1).css(c.cloneCSSValues);if(this.nodeName==="textarea"){g.height("auto")}else{g.width("auto").css({whiteSpace:"nowrap"})}},check:function(l,j){if(!this.clone){this.createClone();this.injectClone()}var i=this.config,m=this.clone,h=this.el,n=h.val();if(n===this.prevValue){return true}this.prevValue=n;if(this.nodeName==="input"){m.text(n);var o=m.width(),k=(o+i.extraSpace)>=i.minWidth?o+i.extraSpace:i.minWidth,g=h.width();k=Math.min(k,i.maxWidth);if((k<g&&k>=i.minWidth)||(k>=i.minWidth&&k<=i.maxWidth)){i.onBeforeResize.call(h);i.onResize.call(h);h.scrollLeft(0);if(i.animate&&!j){h.stop(1,1).animate({width:k},i.animate)}else{h.width(k);i.onAfterResize.call(h)}}return}m.width(h.width()).height(0).val(n).scrollTop(10000);var f=m[0].scrollTop;if(this.previousScrollTop===f){return}this.previousScrollTop=f;if(f+i.extraSpace>=i.maxHeight){h.css("overflowY","");f=i.maxHeight;j=true}else{if(f<=i.minHeight){f=i.minHeight}else{h.css("overflowY","hidden");f+=i.extraSpace}}i.onBeforeResize.call(h);i.onResize.call(h);if(i.animate&&!j){h.stop(1,1).animate({height:f},i.animate)}else{h.height(f);i.onAfterResize.call(h)}},destroy:function(){this.unbind();this.el.removeData("AutoResizer");this.clone.remove();delete this.el;delete this.clone},injectClone:function(){(c.cloneContainer||(c.cloneContainer=d("<arclones/>").appendTo("body"))).append(this.clone)}}})(jQuery);


var syspath = '../../../controller/';
function msgWin(width,on,content,timeout,noclose){
	if(on){
	    var closeBtn = ( noclose == true ) ? '' : '<a class="xbox" href="Javascript:msgWin(null,false)"></a>';
		if(width == null) width = '30%';
		if($("#grayout").length > 0){
			if($("#grayout").css('display') == 'none') {
				$("#grayout").fadeIn('fast');
				$(".msg_wrap").fadeIn('fast');
			}else{
			    $("#grayout").unbind();
			}
			$(".msg").html('loading...');
			$(".msg").animate({
				width:width
			});
			
			if(content != null) $(".msg").html(closeBtn + '<div>'+content+'</div>');
		} else{
			var str = '<div id="grayout"></div><div class="msg_wrap"><div class="msg" style="width:';
			str += width;
			str += ';"><div class="tctr">loading...</div></div></div>';
			$("body").append(str);
			if(content != null) $(".msg").html(closeBtn+'<div>'+content+'</div>');
			$("#grayout").fadeIn('fast');
			$(".msg_wrap").fadeIn('fast');
		}
		var newY = window.pageYOffset + 100;
    	$(".msg_wrap").css('top',newY+'px');
		if(timeout != null) setTimeout('msgWin(null,false)',timeout);
		if(!noclose) $("#grayout").click(function(){msgWin(null,false);$(this).unbind('click');});
	} else {
		if($("#grayout").css('display') == 'block' && $("#grayout").length > 0) {
			$("#grayout").fadeOut('fast');
			$(".msg_wrap").fadeOut('fast',function(){
			    $(".msg").html('');
			});
		}
	}
}
function fillMsg(res){
	$(".msg").html('<a class="xbox" href="Javascript:msgWin(null,false)"></a>'+res);
}
function closeMsgAndOpen(hash){
	msgWin(null,false);
	window.location.hash = hash;
}
var acctMsgShow = false;
var acctMsgKey = 0;
function acctMsg(msg,dur){
    if( $('.acctMsg').length == 0 ) $('body').append('<div class="acctMsg"></div>');
	if( acctMsgShow == true ){
		setTimeout(function(){
		    acctMsg(msg,dur)
		},1000,'30','30');
	} else {
	    var newY = window.pageYOffset + 50;
    	$(".acctMsg").css('top',newY+'px');
		acctMsgShow = true;
		acctMsgKey = Math.round(Math.random()*10000) + 1;
		$('.acctMsg').html('<a class="xbox" href="Javascript:clsAcctMsg('+acctMsgKey+')"></a>' + msg );
		if(dur == null) dur = 8000;
		$(".acctMsg").fadeIn('fast');
		setTimeout('clsAcctMsg('+acctMsgKey+')',dur);
	}
}
function clsAcctMsg(key){
	if(key == acctMsgKey){
		$(".acctMsg").fadeOut('fast');
		acctMsgShow = false;
	}
}
function setDefaultVal (reference,def) {
    var elem = $(reference);
	if(elem.val() != def) elem.removeClass('gray');
	elem.live('focus',function(){
		if( $(this).val() == def ) {
			$(this).val('');
			$(this).removeClass('gray');
		}
	});
	elem.live('blur',function(){
		if( $(this).val() == '') {
			$(this).val(def);
			$(this).addClass('gray');
		}
	});
}
function setAutoResize(elem){
    var $elem = $(elem);
    $elem.autoResize();
}
function deleteCartItem(id){
	$.ajax({
		type:'POST',
		url:syspath+'deleteCartItem.php',
		data:'id='+id,	
		dataType:'text',
		success:function(res){
			if(res == 'true'){
				$("#cart"+id).slideUp('slow',function(){updateCart();});
			}else{
				acctMsg('Sorry, an error occurred deleting this cart item. Sorry for the inconvenience.');
			}
		}
	});
}
function updateCart(){
	$.ajax({
		type:'POST',
		url:syspath+'updateCartContents.php',
		data:'',	
		dataType:'text',
		success:function(res){
			$("#cart-contents").html(res);
		}
	});
}
function cLog(text){
	if(window.console) console.log(text);
}
function aLog(array){
	for(var i = 0; i < array.length; i++){
		cLog('array['+i+']:'+array[i]);
	}
}
function toggleNewsText(){
	if($("#more-news-text").hasClass('hide')) {
		$("#more-news-text").removeClass('hide');
		$("#more-news-link").addClass('hide');
	}
	else {
		$("#more-news-text").addClass('hide');
		$("#more-news-link").removeClass('hide');
	}
}

function toggleEventText(){
	if($("#more-event-text").hasClass('hide')) {
		$("#more-event-text").removeClass('hide');
		$("#more-event-link").addClass('hide');
	}
	else {
		$("#more-event-text").addClass('hide');
		$("#more-event-link").removeClass('hide');
	}
}

function changeNews(index){
	$(".news-container .picture-btns a").removeClass('sel');
	$("#news"+index).addClass('sel');
	$.ajax({
		type:'POST',
		url:syspath+'changeNews.php',
		data:'index='+index,	
		dataType:'json',
		success:function(res){
			if(res.err != 'true'){
				$(".news-container .pic-viewer-window").html(res.html);
			}
		}
	});
}
function changeEvent(index){
	$(".events-container .picture-btns a").removeClass('sel');
	$("#event"+index).addClass('sel');
	$.ajax({
		type:'POST',
		url:syspath+'changeEvent.php',
		data:'index='+index,	
		dataType:'json',
		success:function(res){
			if(res.err != 'true'){
				$(".events-container .pic-viewer-window").html(res.html);
			}
		}
	});
}

function contactFriend(id){
	msgWin(null,true);
	$.ajax({
		type:'GET',
		url:syspath+'contactFriend.php',
		data:'id='+id,	
		dataType:'text',
		success:function(res){
			fillMsg(res);
		}
	});
}

function submitContactFriend(){
	var reply = $("#reply_to").val();
	var subject = $("#subject").val();
	var message = $("#message").val();
	var name = $("#name").val();
	var fid = $("#friend_id").val();
	var vars = 'reply_to='+reply+'&subject='+subject+'&message='+message+'&friend_id='+fid+'&name='+name;
	$.ajax({
		type:'POST',
		url:syspath+'contactFriend.php',
		data:vars,	
		dataType:'text',
		success:function(res){
			if(res != 'true'){
				fillMsg(res);
			}else{
				msgWin(null,false);
				acctMsg('<b>Your message has been sent.</b> We will be responding to you as soon as we can.');
			}
		}
	});
}
function mkMainImg(src,title){
    $("#main-item-img").attr('src','/media/'+src).next().html(title);
}
function enterZipForShipping(){

    var content = '<h2 class="tctr">Just one more thing!</h2><form method="post" action="Javascript:goToPayPal()" class="frm1"><div class="w70 bctr"><fieldset><label for="zip">Enter your US zip code to calculate shipping</label><input type="text" id="zip" name="zip" value="zip code" class="gray w50 tctr bctr block" /></fieldset></div><a class="rad_btn w30 bctr tctr" href="Javascript:goToPayPal()"><span>proceed to</span><span class="paypal-logo">paypal</span><div class="clearfix"></div></a></form>';
    
    msgWin('500px',true,content);
    setDefaultVal('#zip','zip code');
}
function goToPayPal(){

    var vars = 'zip=' + $("#zip").val();
    msgWin(null,true,'<p class="tctr">One moment while we redirect you to </p><div class="paypal-logo hover"></div><div id="paypal-loader" class="bctr mttn"></div><div id="paypal-form-container"></div>',null,true);

    cLog('vars: '+vars);
    $.ajax({
        type:'POST',
        url:syspath+'goToPayPal.php',
        data:vars,  
        dataType:'json',
        success:function(res){
            if(res.err){
                fillMsg(res.html);
            }else if(res.success){
                $("#paypal-form-container").html(res.ppform).removeClass('hide');
                $("#paypal_form").submit();
            }
        }
    });
}
$(document).ready(function(){
	$(".goToUrl").live('click',function(event){
		event.preventDefault();
		var url = $(this).attr('href');
		msgWin('80%',true,'<iframe class="w100" src="'+url+'" style="height:720px"></iframe>');
	});
	if($(".opt-quant").length > 0) setDefaultVal('.opt-quant','0');
	if($("input#pickup").length > 0) {
		$("input#pickup").live('click',function(){
			if($(this).attr('checked')){
				$(".ship-req").each(function(index){
					if($(this).val() == '') $(this).val('not needed');
					$(this).attr('disabled','disabled');
				});
			}else{
				$(".ship-req").each(function(index){
					if($(this).val() == 'not needed') $(this).val('');
					$(this).attr('disabled','');
				});
			}
		});
	}
	if($(".cart-qty").length > 0) {
		$(".cart-qty").live('focus',function(){
			$(this).blur(function(){
				var newVal = $(this).val();
				var id = $(this).attr('id');
				if(!newVal.match(/^[0-9]{1,}$/)){
					$(this).val(0);
					acctMsg('You must enter a number.')
				}
				else if(newVal == 0){
					var c = confirm("Would you like to delete this from your shopping cart?");
					if(c){
						deleteCartItem(id);
					}else{
						updateCart();
					}
				} else{

					var vars = 'cid='+id+'&quantity='+newVal;

					$.ajax({
						type:'POST',
						url:syspath+'updateCart.php',
						data:vars,	
						dataType:'text',
						success:function(res){
							if(res == 'true'){
								updateCart();
							}else{
								acctMsg('<b>There was an error updating your cart.</b> We are sorry for any inconvenience. This has been reported to the admin.');
							}
						}
					});
				}
				$(this).unbind('blur');
				
				
			});
		});
	}
    $("#coupon").keyup(function(event){ 
        var val = $(this).val();
        var count = val.length;
        if(count == 8){
            $("#coupon-typing-msg").fadeOut('slow');
            if($("#coupon-box fieldset label span.err").length == 1){
                $("#coupon-box fieldset label span.err").fadeOut('slow',function(){$(this).remove();});
            }
            // capture shipping
            var shipping = $("#shipping-amt").html();
            var subtotal = $("#subtotal-amt").html();
            var total = $("#grand-total-amt").html();
            // ajax call to check coupon
            $.ajax({
                type:'POST',
                url:syspath+'getCouponDetails.php',
                data:'code='+val+'&shipping='+shipping+'&subtotal='+subtotal+'&total='+total,  
                dataType:'json',
                success:function(res){
                    switch(res.err){
                        case "no-shipping":
                            $("#coupon-amt-box").slideUp('slow');
                            $("#coupon-box fieldset label").append('<span class="err">This coupon only works with shipped orders</span>');
                        break;
                        case "coupon-invalid":
                            $("#coupon-amt-box").slideUp('slow');
                            $("#coupon-box fieldset label").append('<span class="err">This coupon is invalid.</span>');
                        break;
                        case "coupon-used":
                            $("#coupon-amt-box").slideUp('slow');
                            $("#coupon-box fieldset label").append('<span class="err">This coupon has already been used.</span>');
                        break;
                        case "not-found":
                            $("#coupon-amt-box").slideUp('slow');
                            $("#coupon-box fieldset label").append('<span class="err">Coupon not found.</span>');
                        break;
                        default:
                            $("#coupon-msg").html(res.msg);
                            $("#coupon-amt").html(res.amt);
                            $("#grand-total-coupon-amt").html(res.total);
                            $("#grand-total-amt").hide();
                            $("#grand-total-coupon-amt").show();
                            $("#coupon-amt-box").slideDown('slow');
                        break;
                    }
                }
            });
        }else if(count > 8){
            // bring up typing message
            $("#coupon-typing-msg").fadeIn('slow');
            // hide coupon subtotal box
            $("#coupon-amt-box").slideUp('slow');
        }else if(count == 0){
            // hide typing message
            $("#coupon-typing-msg").fadeOut('slow');
            $("#coupon-amt-box").slideUp('slow');
        }else{
            // show typing message
            $("#coupon-typing-msg").fadeIn('slow');
            $("#coupon-amt-box").slideUp('slow');
        }
    });
});
