// function to add to the window's onload
function push_addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function push_buyer_tracking_onload(){
	push_set_cookie_from_URL_param();
	push_show_buyer_discount_top_strip();
}

function push_product_page_onload(){
	push_insert_show_tab_iframe();
	push_buyer_tracking_onload();
}

function push_confirmation_page_onload(){
	push_insert_show_modal_iframe();
	push_init_shadowbox();	
}

///////////////// SHADOWBOX SECTION /////////////
function push_moveCloseLink(){ 
	var cb=document.getElementById('sb-nav-close'); 
	var tb=document.getElementById('sb-wrapper'); 
	if(tb) tb.appendChild(cb); 
}

function push_init_shadowbox(){
	Shadowbox.init({
		onOpen: push_moveCloseLink,
		overlayOpacity: .8,
		fadeDuration:0.4,
		resizeDuration:0.4
	});
}

//function to open shadowbox directly on page load
function push_show_deal_on_page_load(dealID){
	var url = 'http://www.push44.com/modal/showDeal/'+dealID;
	Shadowbox.open({
        content:   	url,
        player:     "iframe",
        title:      "Hello From Push44",
        height:     380,
        width:      960
    });
};

///////////////// END SHADOWBOX SECTION /////////////

//////////////// DEAL DISPLAY HELPERS ///////////////

//function to add push iframe to page
function push_insert_show_tab_iframe(){
	var iframe=document.createElement("iframe");
	var page_url = escape(window.location.protocol+'//'+window.location.hostname);
	iframe.setAttribute("src","http://www.push44.com/iframe/findDeal/"+push_get_merchant_id()+push_get_prod_and_category_ids()+'&url='+page_url+'&action=tab');
	iframe.setAttribute("width","1");
	iframe.setAttribute("height","1");
	iframe.setAttribute("style", "display:none");
	void(document.body.appendChild(iframe));
}

//function to add push iframe to page
function push_insert_show_modal_iframe(){
	var iframe=document.createElement("iframe");
	var page_url = escape(window.location.protocol+'//'+window.location.hostname);
	iframe.setAttribute("src","http://www.push44.com/iframe/findDeal/"+push_get_merchant_id()+push_get_prod_and_category_ids()+'&url='+page_url+'&action=modal');
	iframe.setAttribute("width","1");
	iframe.setAttribute("height","1");
	iframe.setAttribute("style", "display:none");
	void(document.body.appendChild(iframe));
}

//function to extract the merchant id from page HTML
function push_get_merchant_id(){
	return document.getElementById('push44_merchant_id').innerHTML;
}
//function to extract product and category ids from page HTML
function push_get_prod_and_category_ids(){
	var products = document.getElementById('push44_product_ids').innerHTML;
	var categories = document.getElementById('push44_category_ids').innerHTML;
	return '?product_ids='+products+'&category_ids='+categories;
}

//function to set the href of the push us tab
function push_alter_push_tab_href(){
	document.getElementById('push_tab_link').href=document.getElementById('push_tab_link').href+get_merchant_id()+get_prod_and_category_ids();
}

//////////////// END DEAL DISPLAY HELPERS ///////////////


//////////////// BUYER HELPERS ///////////////

// Parse the URL parameters into associative array
var push_urlParams = {};
(function () {
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&;=]+)=?([^&;]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q))
       push_urlParams[d(e[1])] = d(e[2]);
})();

/**
 * If there is a parameter in the URL which corresponds to promo code.
 * set the cookie PushPromoCode to the parameter's value
 *
 * Should run once every page that Merchant plans to have users land
 * on when coming from Push (product pages, category pages, home page)
 */

function push_set_cookie_from_URL_param(){
	// if the promocode was passed as a parameter in the URL
	if("PushPromoCode" in push_urlParams){
		// get the promo code
		var promo_code = push_urlParams["PushPromoCode"];
		
		// set a cookie with the promo code
		push_setCookie('PushPromoCode', promo_code, 90, '/');
	}
	
	if("PushRefID" in push_urlParams){
		//get the referralId
		var refId=push_urlParams["PushRefID"];
		//set a cookie with the referralId
		push_setCookie('PushRefID', refId, 90, '/');
	}
	
}

/**
 * If coupon code set in cookies, applies it to cart
 *
 *
 * Should run once every time user navigates to the page 
 * where he/she would normally enter the coupon code
 * Most likely, this is the cart/checkout page
 */

function push_apply_coupon(){
	//get the promo code from the coookie
	var promo_code = push_getCookie('PushPromoCode');
	
	//get the referral id
	var referralId = push_getCookie('PushRefID');
	
	//the promo code will be null if there was not PushPromoCode cookie
	if(promo_code){
	  	// The coupon code will now be applied to the cart by
		// the normal logic which would happen if the user had
		// manually entered a coupon code and clicked 
		// 'apply coupon' 
		
		// Set promo code value in the textfield for couponcode
		// TO DO FOR MERCHANT: change the id to your textfield's ID
		document.getElementById('promoCode').value=promo_code;
		document.getElementById('pushPromoCode').value="Y";
		
		if (referralId) {
			document.getElementById('referralId').value = referralId;
		}
		
		//We only want to submit it if there was no error
		if (document.getElementById('promoError').value == "N") {
			document.promoCodeForm.submit();
		}
		// Simulate a click on the 'apply coupon' button
		// TO DO FOR MERCHANT: choose appropriate method and change ID or Form Name
		// Depending on your coupon code application architecture, you will simulate a:
		// 1) button click:
		// 	document.getElementById('promoCodeButton')[0].click();
		// 2) form submission:
		// 	document.PromoCodeForm.submit();
	}
}

/** 
 * Returns cookie value if it is set
 */
function push_getCookie(c_name)
{
	if (document.cookie.length>0)
  {
  	c_start=document.cookie.indexOf(c_name + "=");
  	if (c_start!=-1)
    {
    	c_start=c_start + c_name.length+1;
    	c_end=document.cookie.indexOf(";",c_start);
    	if (c_end==-1) c_end=document.cookie.length;
    	return unescape(document.cookie.substring(c_start,c_end));
    }
  }
	return null;
}

/** 
 * Sets cookie value
 */
function push_setCookie(c_name,value,expiredays,path)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toUTCString())+
	((path==null) ? "" : ";path="+path);
}


function push_show_buyer_discount_top_strip()
{
	if("PushBuyerDiscount" in push_urlParams){
		document.getElementById('pushbar').style.display='block';
		document.getElementById('push44_buyer_discount').innerHTML=push_urlParams["PushBuyerDiscount"];
	}
}
//////////////// END HELPERS ///////////


//////////// SALE REPORT HELPERS //////////////////










/////////// END SALE REPORT ///////////////////



