//PLOOM JS

/*** GLOBAL ****/

//check if function exists
jQuery.fn.exists = function(){return jQuery(this).length>0;}

$(document).ready(function() {
						   
	//setup cart buttons
	if(typeof window.loggedIn == 'function'){
		//get customer name
		var customerName = getName();
		
		if(loggedIn()) {
			//display sign out button
			$('#btn_signOut').css("display","block");
			$('#btn_signIn').css("display","none");
			
			//my account link goes to my account page
			$('#my-account').attr("href","https://ploom.worldsecuresystems.com/my-account.html");
			
			//change cart bar color off logged in or out
			$('.shopping-cart-bar').addClass('cart-logged-in');
			
			//show shopping cart bar
			$('.shopping-cart-bar').css("display","block");
			
			//diplay customer name or "Guest"
			$('#customerName').html(customerName);
		}
		else {
			//display sign in button
			$('#btn_signOut').css("display","none");
			$('#btn_signIn').css("display","block");
			
			//open sign in lightbox
			$('#btn_signIn').click(function(){openSignIn()});
			
			//my account link opens sign in lightbox
			$('#my-account').css("display","none");
			$('#spacer').css("display","none");
			
			//show shopping cart bar
			if($('.cartSummaryItem').html() != 'Shopping cart is empty.') {
				$('.shopping-cart-bar').css("display","block");
			}
			
			//diplay customer name or "Guest"
			$('#customerName').html(customerName);
		}
		
		//hover actions for "social" buttons in header
		$('#header #social #icons li a').hover(function(){
			$('#header #social #status img').css('display','none');
			$('#header #social #status #' + $(this).attr('id') + "Status").css('display','block');
		});
	}
		//get idev affiliate ID if exists & create cookie
		var idev = getParameterByName("idev_id");
		
		if(idev != "") {
			//check if cookie already exists
			$.cookie("idev_id", idev, { expires: 120});
		}
});

//get query params by name
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, " "));
}


//open sign in lightbox
function openSignIn() {
	Shadowbox.open({
        content:    "https://ploom.worldsecuresystems.com/signup-lightbox.html",
        player:     "iframe",
        title:      "Login",
        height:     480,
        width:      601
    });

}

//close sign in lightbox
function closeSignIn() {
	Shadowbox.close();
}

//open newsletter signup lightbox
function openNewsletterSignUp() {
	Shadowbox.open({
        content:    "https://ploom.worldsecuresystems.com/newsletter-lightbox.html",
        player:     "iframe",
        title:      "Login",
        height:     515,
        width:      400
    });

}

//open taxes signup lightbox
function openShadowbox(element,title,h,w) {
	Shadowbox.open({
        content:    element.html(),
        player:     "html",
        title:      title,
        height:     h,
        width:      w
    });
}

//hide login, show sign up form
function showSignUp() {
	$('#loginForm').css("display","none");
	$('#signUp').css("display","block");
}

//validate login form
function checkLogin(theForm){
	
	var why = "";
	if (theForm.Username) why += isEmpty(theForm.Username.value, "Username");
	if (theForm.Password) why += isEmpty(theForm.Password.value, "Password");
	if (why != ""){alert(why); return false;}
	
	//pageTracker._linkByPost(theForm);
	
	theForm.submit();
	
	//$("#loginForm").submit();
	
	/*$("#theLogin").ajaxSubmit({
        dataType : 'json',
        success : function (response) {
			alert(response);
            window.parent.pageTracker._link('https://ploom.worldsecuresystems.com/products.html');
        }
    });*/
	
	//window.parent.pageTracker._link('https://ploom.worldsecuresystems.com/products.html');

	return false;
}

//validate login form on checkout
function checkLoginCheckout(theForm){
	
	var why = "";
	if (theForm.Username) why += isEmpty(theForm.Username.value, "Username");
	if (theForm.Password) why += isEmpty(theForm.Password.value, "Password");
	if (why != ""){alert(why); return false;}
	
	//pageTracker._linkByPost(theForm);
	
	theForm.submit();

	return false;
}

var submitcount11881 = 0;

function checkAge() {
	var ofAge = false;
		
	var today = new Date();
	var curryear = today.getFullYear();
	var currmonth = today.getMonth();
	var currday = today.getDate();
	
	var birth = $('#DOB').val();
	
	var birthyear = $('#birthyear').val();
	var birthmonth = $('#birthmonth').val();
	var birthday = $('#birthday').val();
	
	if (birthyear != " " && birthmonth != " " && birthday != " ") { 
		//set birthday to be entered in system
		$('#DOB').val(birthday + "-" + birthmonth + "-" + birthyear);
	}
	else {
		$('#DOB').val("Date of Birth");	
	}
	
	//convert month name
	if(birthmonth == "Jan") { birthmonth = 0 }
	if(birthmonth == "Feb") { birthmonth = 1 }
	if(birthmonth == "March") { birthmonth = 2 }
	if(birthmonth == "Apr") { birthmonth = 3 }
	if(birthmonth == "May") { birthmonth = 4 }
	if(birthmonth == "Jun") { birthmonth = 5 }
	if(birthmonth == "Jul") { birthmonth = 6 }
	if(birthmonth == "Aug") { birthmonth = 7 }
	if(birthmonth == "Sep") { birthmonth = 8 }
	if(birthmonth == "Oct") { birthmonth = 9 }
	if(birthmonth == "Nov") { birthmonth = 10 }
	if(birthmonth == "Dec") { birthmonth = 11 }
	
	if ($('#DOB').val() != "Date of Birth") { 
		if ((curryear - birthyear) == 18) {
			if(currmonth > birthmonth){
				ofAge = true;
			}
			else if(currmonth == birthmonth) {
				if(currday >= birthday){
					ofAge = true;
				}
			}
		}
		
		if ((curryear - birthyear) > 18) {
			ofAge = true;
		}
	}
	
	if(ofAge == false){
		jConfirm('Sorry, we take age limits very seriously.  If you are under 18, we can not sell you Ploom products.', 'Confirmation Dialog', function(r) {
			if (true) {
				location.href = "http://ploom.com/age";
			}
		});
		
	}
	return ofAge;
}

//validate signup form
function checkSignUp(theForm){
	var why = "";
	if (theForm.FirstName) why += isEmpty(theForm.FirstName.value, "First Name");
	if (theForm.LastName) why += isEmpty(theForm.LastName.value, "Last Name");
	if (theForm.EmailAddress) why += checkEmail(theForm.EmailAddress.value);
	if (theForm.Username) why += isEmpty(theForm.Username.value, "Username");
	if (theForm.Password && theForm.PasswordConfirm) { why += isEmpty(theForm.Password.value, "Password");
	if (theForm.Password.value.length < 6) why += appendBreak("- Password must be 6 characters or longer."); }
	if (theForm.CAT_Custom_152626) why += checkDropdown(theForm.CAT_Custom_152626.value, "Date of Birth Year");
	if (theForm.CAT_Custom_152631) why += checkDropdown(theForm.CAT_Custom_152631.value, "Date of Birth Day");
	if (theForm.CAT_Custom_152632) why += checkDropdown(theForm.CAT_Custom_152632.value, "Date of Birth Month");
 	if(why != ""){alert(why);return false;}

	if (theForm.CAT_Custom_152626 && theForm.CAT_Custom_152631 && theForm.CAT_Custom_152632) {
	
		var ofAge = false;
		
		var today = new Date();
		var curryear = today.getFullYear();
		var currmonth = today.getMonth();
		var currday = today.getDate();
		
		var birthyear = theForm.CAT_Custom_152626.value;
		var birthmonth = theForm.CAT_Custom_152632.value;
		
		//convert month name
		if(birthmonth == "January") { birthmonth = 0 }
		if(birthmonth == "February") { birthmonth = 1 }
		if(birthmonth == "March") { birthmonth = 2 }
		if(birthmonth == "April") { birthmonth = 3 }
		if(birthmonth == "May") { birthmonth = 4 }
		if(birthmonth == "June") { birthmonth = 5 }
		if(birthmonth == "July") { birthmonth = 6 }
		if(birthmonth == "August") { birthmonth = 7 }
		if(birthmonth == "September") { birthmonth = 8 }
		if(birthmonth == "October") { birthmonth = 9 }
		if(birthmonth == "November") { birthmonth = 10 }
		if(birthmonth == "December") { birthmonth = 11 }
		
		var birthday = theForm.CAT_Custom_152631.value;
		
		if ((curryear - birthyear) == 18) {
			if(currmonth > birthmonth){
				ofAge = true;
			}
			else if(currmonth == birthmonth) {
				if(currday >= birthday){
					ofAge = true;
				}
			}
		}
		
		if ((curryear - birthyear) > 18) {
			ofAge = true;
		}
		
		if(!ofAge){
			jConfirm('Sorry, we take age limits very seriously.  If you are under 18, we can not sell you Ploom products.', 'Confirmation Dialog', function(r) {
				if (true) {
					location.href = "http://ploom.com/age";
				}
			});
			return false;
		}
		
		if(submitcount11881 == 0){submitcount11881++;theForm.submit();return false;}else{alert("Form submission is in progress.");return false;}
	
	}
}

//validate signup form
function checkSignUpCheckout(theForm){
		
		var why = "";
		
		if (theForm.EmailAddressGuest) why += checkEmail(theForm.EmailAddressGuest.value);
		
		if(why != ""){alert(why);return false;} else{ 
			
			if(checkAge()) { guestRegister(theForm); return false; }
			
			return false;}
}

//check newsletter
function checkNewsletter(theForm) {var why = "";if (theForm.EmailAddress) why += checkEmail(theForm.EmailAddress.value); if (why != ""){alert(why);return false;}theForm.submit();return false;}

function guestRegister(theForm) {
	$('#checkoutForm #EmailAddress').val(theForm.EmailAddressGuest.value);
	showHideGuestCheckout(false);
}

function showHideGuestCheckout(show) {
	if(show) {
		$('#guestCheckout').css("display","block");
		$('#checkoutWrapper').css("display","none");
	}
	else{
		$('#guestCheckout').css("display","none");
		$('#checkoutWrapper').css("display","block");
	}
}	

//replace view cart link with secure URL
function trackCheckout() {
	
	$("#catshopbuy").removeAttr("onclick");
	
	//get check out button link
	var cartLink = $("#catshopbuy").attr("href");
	
	//var newCartLiink = $("#catshopbuy").attr("href", cartLink + "&" + $.cookie("__utmz"))
	
	if($("#catshopbuy").length != 0) {
		$("#catshopbuy").click(function() {
				
			doAlert();
			
			//get orderID from link
			var orderID = cartLink.substring(cartLink.indexOf("OrderID=") + 8, cartLink.indexOf("&CheckOut"));
			
			//remove default click handler & href to avoid double validation & linking
			$("#catshopbuy").removeAttr("href");
			
			//if shopping cart passes validation, track the link
			if(ValidateCart(orderID) == true) {
				pageTracker._link(cartLink); return false;
				//document.location = $("#catshopbuy").attr("href");
			}
		});
	}
}

function trackViewCart() {
	
	/*if($('.cartSummaryItem').html() != "Shopping cart is empty.") {	
		$('#cartLink').css("display","block");
	}*/
	
	
	
	var cartLink = "https://ploom.worldsecuresystems.com" + $('.cartSummaryLink').attr('href');
	
	$('.cartSummaryLink').attr("target", "_top");
	$('.cartSummaryLink').attr("onclick","pageTracker._link(cartLink); return false;");
}

var countit = 1;

//do alert 
function doAlert() {
	countit++;
	var theState = $('#shippingState');
	var checkoutButton = $('#catshopbuy');
	var checkoutOff = $('#checkout-off');
	var accessDenied = "";
	
	accessDenied = checkForTobacco();
	
	//WASHINGTON STATE
	//alert();
	 if(theState.val()==49273) {
		
		 if(accessDenied){
			  alert('Tobacco sales to Washington State are prohibited, but you may purchase one of our herbal blends if you\'d like. Please remove tobacco products from your cart to proceed with checkout.');
			 checkoutButton.css("display", 'none');
			 checkoutOff.css("display","inline");
			 
			 return false;
		 }
		 else{
			checkoutButton.css("display", "inline");
			checkoutOff.css("display","none");
		}
	}
	
	accessDenied = checkForButane();
	
	//ALASKA & HAWAII
	if(theState.val()==49227 || theState.val()==49237) {
	
		 if(accessDenied){
			  alert('Unfortunately, due to shipping retrictions we cannot ship butane to Alaska and Hawaii at this time. To proceed with checkout please remove butane products from your cart (*Note - Starter Kit contains butane).');
			 checkoutButton.css("display", 'none');
			 checkoutOff.css("display","inline");
			 
			 return false;
		 }
		 else{
			checkoutButton.css("display", "inline");
			checkoutOff.css("display","none");
		}
	}
	
	return(true);
	
}

//check product names for string "tobacco"
function checkForTobacco(){
	var theNames = getElementsByClassName("productitemcell", false);

	for(var i = 0; i < theNames.length; i++){
		  if(theNames[i].firstChild.nodeValue != null){
				 if(theNames[i].firstChild.nodeValue.indexOf("Tobacco", 0) != -1 || theNames[i].firstChild.nodeValue.indexOf("Starter", 0) != -1){

					$("#shippingState").removeOption("49273");
					
					 return true;
				 }
		 }
	}
	return false;
}

//check shopping cart for butane products
function checkForButane(){
	
	//copy all options to placeholder select
	//$("#ShippingOptions").copyOptions("#ShippingOptionsHolder","all");
	
	var theNames = getElementsByClassName("productitemcell", false);
		
	for(var i = 0; i < theNames.length; i++){
		  if(theNames[i].firstChild.nodeValue != null){
				
				if(theNames[i].firstChild.nodeValue.indexOf("Butane", 0) != -1 || theNames[i].firstChild.nodeValue.indexOf("Starter", 0) != -1){
					/*
					//clear shipping options from placeholder
					$("#ShippingOptionsHolder").removeOption(/./); 
					
					//copy all options to placeholder select
					$("#ShippingOptions").copyOptions("#ShippingOptionsHolder", "all");
					
					*/
				  	$('#spangroundonly').css("display", "block");
					/*
					//hide al options but UPS Ground & FREE
					$("#ShippingOptions").removeOption("62075");
					$("#ShippingOptions").removeOption("62046");
					$("#ShippingOptions").removeOption("61591");
					*/
					
					$("#shippingState").removeOption("49227");
					$("#shippingState").removeOption("49237");
					
					 return true;
				 }
				 else {
					 //show all shipping options by retrieving from placeholder
					/*$("#ShippingOptions").removeOption(/./); 
					
					$("#ShippingOptionsHolder").copyOptions("#ShippingOptions", "all");
					
					*/
					$('#spangroundonly').css("display", "none");
				 }
				 
		 }
	}
	return false;
}

function parseCookies() {
	//
	// Get the __utmz cookie value. This is the cookies that
	// stores all campaign information.
	//
	var z = $.cookie("__utmz");
	//
	// The cookie has a number of name-value pairs.
	// Each identifies an aspect of the campaign.
	//
	// utmcsr  = campaign source
	// utmcmd  = campaign medium
	// utmctr  = campaign term (keyword)
	// utmcct  = campaign content (used for A/B testing)
	// utmccn  = campaign name
	// utmgclid = unique identifier used when AdWords auto tagging is enabled
	//
	// This is very basic code. It separates the campaign-tracking cookie
	// and populates a variable with each piece of campaign info.
	//
	if(z.indexOf("utmcsr=") != -1) {
		var source  = z.substring(z.indexOf("utmcsr=") + 7, z.indexOf("|"));
		alert(source);
	}
	
	if(z.indexOf("utmcmd=") != -1) {
		var medium  = z.substring(z.indexOf("utmcmd=") + 7, 99999);
	}
	var term  = z.substring(z.indexOf("utmctr=") + 7, z.indexOf("|"));
	var content  = z.substring(z.indexOf("utmcct=") + 7, z.indexOf("|"));
	var campaign = z.substring(z.indexOf("utmccn=") + 7, z.indexOf("|"));
	var gclid = z.substring(z.indexOf("utmgclid=") + 9, z.indexOf("|"));
	
	
	alert(medium);
	alert(term);
	alert(content);
	alert(campaign);
	alert(gclid);
	
	/*
	var medium  = _uGC(z, 'utmcmd=', '|');
	var term    = _uGC(z, 'utmctr=', '|');
	var content = _uGC(z, 'utmcct=', '|');
	var campaign = _uGC(z, 'utmccn=', '|');
	var gclid   = _uGC(z, 'utmgclid=', '|');
	*/
}


function AddCheckoutEvent(func){
	/*var theClick = $('#catshopbuy').attr("onclick");
	
	theClick = $('#catshopbuy').attr("onclick","return doAlert(); " + theClick);
	
	//choose first shipping option
	var shippingOptions = document.getElementById('ShippingOptions');
	
	if (shippingOptions.selectedIndex == 0) {
	   shippingOptions.selectedIndex = 1;
	}
	*/

	//$('#catshopbuy').live('change', function() {doAlert(); } );
	
  var btn = document.getElementById('catshopbuy');
  var oldonclick = btn.onclick;
  //alert (oldonclick);
	if (typeof btn.onclick != 'function'){
		 btn.onclick = func;
		  }
	else{
		 btn.onclick = function() {
			 
			if(func()) {
				return oldonclick();
			}
			else {
				return false;	
			}
			
		 };
	 }
	
	 	/*
	 function UpdateShipping(c,e,b){
    var d=document.getElementById("catCartDetails");
		if(d){
			var a=CMS.OrderRetrievev2.ServerSideUpdateShipping(e,c,b);
			if(a.value[0]){
				d.innerHTML=a.value[2]
			}
			else{    
				d.innerHTML=a.value[2]
			}
			if(a.value[1].length>0){
			alert(a.value[1])
			}
		}
	 }
	  */
}

//hide elements by class
var allHTMLTags = new Array();
	
function hideElementByClass(theClass) {
	
	//Create Array of All HTML Tags
	var allHTMLTags=document.getElementsByTagName("div");
	
	//Loop through all tags using a for loop
	for (i=0; i< allHTMLTags.length; i++) {
	
	//Get all tags with the specified class name.
	if (allHTMLTags[i].className==theClass) {
	
	//Place any code you want to apply to all
	//pages with the class specified.
	//In this example is to "display:none;" them
	//Making them all dissapear on the page.
	
	allHTMLTags[i].style.display='none';
	
	 }
  }
}

//get all product names
function getElementsByClassName(classname, node)  {
    if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

//jQuery regex
jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ? 
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function affiliateLifetimeCommission(fn,ln,eadd) {
	
	//populate form fields
	$('#FirstNameAffiliate').val(fn);
	$('#LastNameAffiliate').val(ln);
	$('#EmailAddressAffiliate').val(eadd);
	$("#affiliateReferralID").val($.cookie("idev_id"));
	
	//set affiliate ID if exists
	if($.cookie("idev_id") != null) {
		
		//submit affiliate tracking reference ID
		var $f = $('#affiliateForm');
		
		$.ajax({
			type: 'POST',
			url: $f.attr('action'), // form URL as generated by module
			data: $f.serialize(), // serialised form data
			success: function(msg) {
				if (msg.charAt(0) === '{') {
					eval('var o = ' + msg);
					if (o.FormProcessV2Response.success) {
						//alert('');
					}
				}
			},
			error: function(msg) {
				alert('error'+msg);
				return false;
			}
		});

	}	
}

//ADD NEW ON CLICK EVENT FOR CHECKOUT BUTTON ON CART
function addCartEvent() {
	var btn = document.getElementById('catshopbuy');
  	var oldonclick = btn.onclick;
  //alert (oldonclick);
	 btn.onclick = function() {
		 
		if(checkUPS()) {
			return oldonclick();
		}
		else {
			return false;	
		}
		
	 };
}

//CHECK CART FOR UPS SHIPPING, IF YES APPEND PO QUERY VAR
function checkUPS() {
	//alert("HI");
	var curhref = $('#catshopbuy').attr("href");
	var newhref = "&ups=1";
	
	if($('#ShippingOptions').val() == 61584 || $('#ShippingOptions').val() == 83128) {
		$('#catshopbuy').attr("href",curhref + newhref);
	}
	
	return true;
}

//ADD NEW ON CLICK EVENT FOR PURCHASE BUTTON
function addCheckoutEvent() {
	//$('#placeorder').attr("onclick", "return checkPOBox()");
}

//CHECK IF SHIPPING UPS, IF YES DO NOT ALLOW SHIP TO PO BOX
function checkPOBox() {
	var ups = getParameterByName("ups");
	var ShippingAddress = document.getElementById('ShippingAddress').value;
	
	if(ups == 1){
		if( ShippingAddress.indexOf("box") != -1 || ShippingAddress.indexOf("Box") != -1) {
			alert("Unfortunately UPS cannot ship to PO Boxes. Please update your shipping address or go back to your shopping cart and choose a new shipping method");
			return false;
		}
	}
}
