var $j = jQuery.noConflict();
/**
02.* Get CSS jQuery extension
03.* @param {Object} $
04.*/
(function($){
    $.getCSS = function( url, media ){
        $(document.createElement('link') ).attr({
            href: url,
            media: media || 'screen',
            type: 'text/css',
            rel: 'stylesheet'
        }).appendTo('head');
    }
})(jQuery);
function selectmaintab(tabhash) {

    $j(".topflash").css("display","none");
    $j("#topflash_"+tabhash).css("display","block");

    $j(".tabmenu").css("display","none");   
    $j("#tabmenu_"+tabhash).css("display","block"); 
    
    $j('.tabhome').css("display","none");
    $j('#tabhome_'+tabhash).css("display","block");
}
/* Response handler for user details form when register_user ajax method was called*/
function response_register_user(data) {
    if (data.error) {
        $j("#userdetails_error").html(data.error);
    } else {
        $j("#registration_intro").hide();
        $j("#userdetails").hide();
        $j("#thankyouregister").show();
        $j.post('/actions/login.php',{ member_user: data.username, member_pass: data.password})
        setTimeout('window.location = "'+data.url_root+'"',5000);
    }
}

/* Response handler for user details form when update_user ajax method was called*/
function response_update_user(data) {
    if (data.expired) {
        $j("#userdetails").hide();
        $j("#sessionexpired").show();
        setTimeout('window.location = "'+data.url_root+'"',5000);                    
    } else {
        if (data.success) $j.jGrowl(data.success);
        if (data.error) $j.jGrowl(data.error);                  
    }
}

function ordermultiple(arg){
    if (arg.selector===undefined) return false;

    var addstring='';

    $j(arg.selector).each(function(){

        var stock=parseInt($j(this).next().val());
        var items=0;
        if (this.value>0){
            if (this.value>stock){
                items=stock;
            } else {
                items=this.value;
            }

            id=new String(this.id);
            if (id.indexOf('product_')!=-1){
                id=this.id.substr(8);
            } else {
                id=this.id;
            }
			
            if (cc[id] && cc[id]>0 && (arg.watchforcart!==undefined && arg.watchforcart)){
                stock=stock-items-cc[id];
            } else {
                stock=stock-items;
            }
            
            addstring+=id+"_"+this.value+"^";

            if (stock<=0){
                disableproduct($j(this));
            } else {
                // $j(this).attr('stock', stock);
                $j(this).next().val(stock);
            }
            
            if (arg.clearinputs!==undefined && arg.clearinputs)
                this.value="";
        }
    });
        
    if (addstring)
        $j.post("/ajaxer.php", {method: 'add_to_cart', ps: addstring}, function(data){
            data = eval("(" + data + ")");
            eval(data.cart);
            eval(data.message)
        });
        
}

function bindinstock(){

    $j(".txt_prod_summary[type!=hidden]").each(function(){
        $j(this).keyup(function(e){
            id=this.id.substr(8);
            
            if(( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))) { return false; } else { } 
            $j('#update_button_'+id).css('visibility', 'visible');
            
            var stock=parseInt($j(this).next().val());
            if (cc[id] && location.pathname!='/actions/checkout.php') stock-=cc[id];
            if (this.value > stock){
                if (stock<=0){
                    var message='Sorry, this item is out of stock.'+"\n";
                    if (cc[id]) message+=' There are '+cc[id]+' items of this product in your cart though.';
                    $j.jGrowl(message);
                    disableproduct($j(this));
                } else {
                    this.value=stock;
                    var items = stock==1? "item" : "items";
                    $j.jGrowl('Sorry, only '+stock+' '+items+' in stock available');
                }
            } else {
                $j(this).removeClass('insufficient-stock');
                $j(this).unbind('mouseover');
            }
        });
    });

}

function disableproduct(obj){
    obj.attr('disabled', true);
    obj.val('');
    obj.css('background-color', 'rgb(128,128,128)');
}

function addtocart(productid, qty){
    if (qty>0){
        $j.post("/ajaxer.php", {method: 'add_to_cart', ps: productid+"_"+qty+"^" }, function(data){
            data = eval("(" + data + ")");   
            message = eval(data.message);
            cart = eval(data.cart);
            stockamount=$j('#'+productid).next().val()-qty;
            if (cc[productid]) stockamount-=cc[productid];
            if (stockamount<=0) {
                stockamount=0; $j('#'+productid).attr('disabled', true);
            }
            $j('#'+productid).next().val(stockamount);
        } /* , 'json' */);
    }
}

$j(document).ready(function(){
    bindinstock();

    $j(".notifierlink").click(function(e){
        tooltip($j(this).attr("href"), e, $j(this).attr("id"), $j(this).attr("name"), $j(this).attr("title")); return false;
    });

    $j(".addtocartbutton").click(function(){
        ordermultiple({
            selector: ".txt_prod_summary[type!=hidden]",
            clearinputs: true
        });
    });

    $j('.addtobookmarkhref').text('Add to bookmark');

});

function readmore(category_id){
  $j("#cat_" + category_id).find(".readmore").css("display","block");
  $j("#readmore_link_" + category_id).css("display","none");  
  $j("#readless_link_" + category_id).css("display","inline");  
}
function readless (category_id){
  $j("#cat_" + category_id).find(".readmore").css("display","none");
  $j("#readmore_link_" + category_id).css("display","inline");  
  $j("#readless_link_" + category_id).css("display","none");  
}

function bulk_copy_form_fields(from, to){
    $j("[name*='"+from+"']").each(function(){
        $j(this).val($j("[name='"+this.name.replace(from, to)+"']").val());
        $j(this).parents('form').validate().element( this );
    });
}

function copy_billing_address(id){
    if($j('#'+id).is(':checked')  == true){
        bulk_copy_form_fields('billing_', 'delivery_');
        // initialize country and state boxes
        initCountry(
            'member_billing_country',
            'member_billing_state',
            $j('#member_delivery_country').val(),
            $j('#member_delivery_state').val()
        );
        $j("#userdetailsform").validate().element($j('#member_billing_country'));
        $j("#userdetailsform").validate().element($j('#member_billing_state'));
    } else {
        $j("[name*='billing_']").each(function() {
            $j(this).val('');
            $j("#userdetailsform").validate().element( this );
        });
        $j('#billing_country').val('AU');
        initCountry(
            'member_billing_country',
            'member_billing_state',
            'AU',
            ''
        );
        $j("#userdetailsform").validate().element($j('#member_billing_state'));
    }
    // rebuild styled selects
    $j('#billing_country').parents('.selectcountry-and-state').find('.newListSelected').remove();
    $j('#billing_country').parents('.selectcountry-and-state').find('select.stylable').sSelect();
    
    // show/hide country select as needed
    
    if ($j('#billing_country').val()) {
        $j('#billing_country').parents('.selectcountry-and-state').find('.countryselect').hide();
    } else {
        $j('#billing_country').parents('.selectcountry-and-state').find('.countryselect').show('fast');            
    };
}

function copy_checkout_detail(id)
{
    if($j('#'+id).is(':checked')  == true){
        bulk_copy_form_fields('billing', 'delivery');
        initCountry(
            'billing_country',
            'billing_state',
            $j('#delivery_country').val(),
            $j('#delivery_state').val()
        );
    } else {
        $j("[name*='billing']").val('');
        initCountry(
            'billing_country',
            'billing_state',
            'AU',
            ''
        );
    }    
}

function registerAllVariable( div, file, param )
{ 

var fullurl="/actions/contactUs.php?n=" + $j('#name').val() + "&e=" + $j( '#email' ).val() + "&p=" + $j( '#phone' ).val() + "&m=" + $j('#message').val();
$j.get(fullurl, null, function (data){
		if(data!=1){
			$j("#contactUs").html('<img src="/images/naturalcandles/messagesent.gif"/>');
			$j("#message_det_form").css("display","none");
			$j("#info_message").css("display","");
		} else {
			$j("#contactUsHint").html(data);
		}
	});

} 
function registerAllVariable_contact( div, name, email, phone, message )
{

$j.post("/actions/contactUs.php", {
		n: name,
		e: email,
		p: phone,
		m: message
	}, function (data){
		if(data!=1){
			$j("#contactUs").html('<img src="/images/naturalcandles/messagesent.gif"/>');
			$j("#message_det_form").css("display","none");
			$j("#info_message").css("display","");
		} else {
			$j("#contactUsHint").html(data);
		}
});

} 

function add_to_credit(credit_left,credit_id)
{
	if(document.getElementById("credit_amt_"+credit_id).value>credit_left)
	{
		alert("You Cannot Use Credit amount more than available credit");
  
		 return false;
	}
}

var intervalID, dissapearId;
var height = 0;
var elem;
var open1 = false;

function add_to_order_open( order_id ){
	var url = new String( "/actions/add_to_existing_order.php?order_id=" );
	url += order_id;
	document.location.href=url;
}

function hide_product_block( order_id ) {
	var elem = new String( "product_table_" );
	elem += order_id;
	document.getElementById( elem ).style.display = 'none';
}

function add_bookmark(n, elem){
    
	$j.post("/ajaxer.php", {method : "add_bookmark", pid : n }, function (d){
           switch(d.message){
               case 1:
                   $j.jGrowl('Product added to your bookmark successfully');
                   if (elem) $j(elem).hide();
               break;

           }
           
    }, 'json');
    
}

function delete_bookmark(n){
    $j.post("/ajaxer.php", {method : "remove_bookmark", product_id : n }, function(d){
        $j('#b_product_'+n).hide();
    });
} 

function  user_msg(){
var url="/actions/user_msg.php";
$j.get(url, null, function(data){
	$j("#user_msg").html(data);
});
} 

function  user_msg_all(){
var url="/actions/user_msg_all.php";
$j.get(url, null, function(data){
	if (data!=1){
		$j("#msg_notification_all").css("display","");
		$j("#user_msg_all").html(data);
	} else {
		$j("#msg_notification_all").css("display","none");
	}
});
}
 
function sendEmailNotification( divID, pID, nID ) {
    $j.post("/actions/outOfStock.php?pid=" + pID + "&email=" + $j( '#outOfStockEmail_outofstocknotifier' ).val() + "&did=" + divID + "&n=" + nID,
    null, null, 'script');
}

function tooltip(id, e, pid, instockdate, ptitle){
    var obj=$j("#outofstocknotifier");

obj.css("top", e.pageY-200);
obj.css("left", e.pageX-150);
obj.show();

obj.html('<table width="300" border="0" align="center" cellpadding="0" cellspacing="0"><tr><td width="7" valign="top"><img src="/images/naturalcandles/cor1.jpg" width="7" height="7" /></td><td valign="top" background="/images/naturalcandles/line1.jpg"><img src="/images/naturalcandles/line1.jpg" width="2" height="7" /></td><td width="6"><img src="/images/naturalcandles/cor2.jpg" width="6" height="7" /></td></tr><tr><td background="/images/naturalcandles/line4.jpg"><img src="/images/naturalcandles/line4.jpg" width="7" height="1" /></td><td bgcolor="#ebebeb">	<b><div id="error_outofstocknotifier"></div></b>	<div align="center"><table width="100%"  border="0" cellspacing="0" cellpadding="0"><tr><td width="71%" align="left" class="textprodcolor"><b>Out of stock notification</b></td><td width="29%" align="left" class="textprodcolor"><div align="right"><a class="closeButton" onClick="$j(\'#outofstocknotifier\').hide();"><u>close</u></a></div></td></tr><tr><td colspan="2" align="left" style="font-family: Verdana; font-size: 10px; font-weight: normal">Estimated Back in Stock Date : '+instockdate+'</td></tr><tr><td colspan="2" align="left" style="font-family: Verdana; font-size: 10px; color: #000000; font-weight: normal">Please enter your email address and we will<br> send you an email notification when new stock<br>for '+ptitle+' is available.</td></tr><tr><td colspan="2" align="left"><input name="text" type="text" class="form_login_field_long" id="outOfStockEmail_outofstocknotifier" style="width:250px" size="50"/></td></tr><tr><td colspan="2" align="right"><a href="javascript:sendEmailNotification( \'outofstocknotifier\', \''+pid+'\', \''+pid+'\' );"><img src="/images/naturalcandles/sendred.gif" border="0" /></a></td></tr></table></div>	</td><td background="/images/naturalcandles/line2.jpg"><img src="/images/naturalcandles/line2.jpg" width="6" height="1" /></td></tr><tr><td><img src="/images/naturalcandles/cor4.jpg" width="7" height="8" /></td><td background="/images/naturalcandles/line3.jpg"><img src="/images/naturalcandles/line3.jpg" width="1" height="8" /></td><td><img src="/images/naturalcandles/cor3.jpg" width="6" height="8" /></td></tr></table>');

}

// Old new_added.js below

	function userssss(){
	$j.post("/ajaxer.php", { method: "get_outofstockandusermessage" }, function(data){
		$j("#cart_content").html(data.cart_content);

		if (data.usermsg==""){
			$j("#msg_notification").css("display", "none");
		} else {
			$j("#msg_notification").css("display", "");
			$j("#user_message").html(data.usermsg);
		}
	}, 'json');
	} 


	function closeNotification(){
	$j("#user_notificatio").css('display',"none");
	}
		
	function showDiv(){
	document.getElementById("showDiv").style.display="block";
	}
	

function check_supported_browsers() {
    var browser_version = detectBrowserVersion();
    var browser_accepted = true;
    if($j.browser.msie) {
		if(browser_version<7) {
            browser_accepted = false;
		}
	}
    if($j.browser.mozilla) {
        // 1.9.0.0: FF 3.0
        // 1.9.2.5: FF 3.5
        // 1.9.2.6: FF 3.6.6
        // 1.9.2.13: FF 3.6.13
        currentversion = parseVersionString($j.browser.version);
        minimumversion = parseVersionString('1.9.2.6');
		if(currentversion<minimumversion) {
            browser_accepted = false;
		}
	}
    if($j.browser.safari) {
        // 531: safari 4
		if($j.browser.version<'531') {
            browser_accepted = false;
		}
	}
	
    if($j.browser.chrome) {
		if(browser_version<9) {
            browser_accepted = false;
		}
	}
	
	if (!browser_accepted) {
        alert('Dear Customer, we have detected that you are using an out of date website browser, in order to use the lastest features of our website, you will need to do a free update by proceeding to download the latest website browser. Additional information and tips on updating can be found by viewing our HELP section under GENERAL INFO > Website Browsers');
    }
}	
function detectBrowserVersion(){
    var userAgent = navigator.userAgent.toLowerCase();
    $j.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
    var version = 0;
    
    // Is this a version of IE?
    if($j.browser.msie){
        userAgent = $j.browser.version;
        userAgent = userAgent.substring(0,userAgent.indexOf('.'));
        version = userAgent;
    }

    // Is this a version of Chrome?
    if($j.browser.chrome){
        userAgent = userAgent.substring(userAgent.indexOf('chrome/') +7);
        userAgent = userAgent.substring(0,userAgent.indexOf('.'));
        version = userAgent;
        // If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
        $j.browser.safari = false;
    }

    // Is this a version of Safari?
    if($j.browser.safari){
        userAgent = userAgent.substring(userAgent.indexOf('safari/') +7);
        userAgent = userAgent.substring(0,userAgent.indexOf('.'));
        version = userAgent;
    }

    // Is this a version of Mozilla?
    if($j.browser.mozilla){
        //Is it Firefox?
        if(navigator.userAgent.toLowerCase().indexOf('firefox') != -1){
            userAgent = userAgent.substring(userAgent.indexOf('firefox/') +8);
            userAgent = userAgent.substring(0,userAgent.indexOf('.'));
            version = userAgent;
        }
        // If not then it must be another Mozilla
        else{
        }
    }

    // Is this a version of Opera?
    if($j.browser.opera){
        userAgent = userAgent.substring(userAgent.indexOf('version/') +8);
        userAgent = userAgent.substring(0,userAgent.indexOf('.'));
        version = userAgent;
    }
    return version;
}
function parseVersionString (str) {
    if (typeof(str) != 'string') { return false; }
    var x = str.split('.');
    // parse from string or default to 0 if can't parse
    var maj = parseInt(x[0]) || 0;
    var min = parseInt(x[1]) || 0;
    var pat = parseInt(x[2]) || 0;
    var bld = parseInt(x[3]) || 0;
    return {
        major: maj,
        minor: min,
        patch: pat,
        build: bld
    }
}

