/*--------------------------------------------------------------------------*
 * 
 * Copyright (C) 2011 Brand Labs LLC
 * 
 *--------------------------------------------------------------------------*/

var urlCoupon = Class.create({
	COOKIE_NAME: 'couponCookie',
	
	initialize: function() {
	
	
		this.links = $$('a[class="urlCoupon"]');
		if(this.links == undefined || this.links == null) {
			return;
		}
			
		this.links.each(function(element) {
			Event.observe(element,'click', this.handleClick.bindAsEventListener(this));
			}.bind(this));
		
		this.urls = $$('form[name="urlForm"]');
		if(this.urls == undefined || this.urls == null) {
			return;
		}
		
		this.urls.each(function(element) {
			Event.observe(element,'submit', this.handleSubmit.bindAsEventListener(this));
			}.bind(this));	
},

	handleSubmit: function(event) {
		Event.stop(event);
		var form  = Event.element(event);
		if(form == undefined || form == null) {
			return;
		}
		var ref = form['couponUrl'].getValue();
		if(ref == undefined || ref == null) {
			return;
		}
		var prodHash = $H(ref.toQueryParams());
		var couponCode = prodHash.unset('CouponCode');
		var url = "/ShoppingCart.asp?" + prodHash.toQueryString();
		
		//if coupon cookie exist, delete it and create new one
		if(doesCookieExist(this.COOKIE_NAME)) {
			deleteCookie(this.COOKIE_NAME);
		}
		if(couponCode == undefined || couponCode == null) {
			window.location.href = url;
		}
		else {
			addCookie(this.COOKIE_NAME, couponCode);
			window.location.href = url;
		}
	
},
	handleClick: function(event) {
		Event.stop(event);
		var ref = Event.element(event).readAttribute('href');
		if(ref == undefined || ref == null) {
			ref = Event.element(event).up().readAttribute('href');
		}
		if(ref == undefined || ref == null) {
			return;
		}
		var prodHash = $H(ref.toQueryParams());
		var couponCode = prodHash.unset('CouponCode');
	
		var url = "/ShoppingCart.asp?" + prodHash.toQueryString();
	
		//if coupon cookie exist, delete it and create new one
		if(doesCookieExist(this.COOKIE_NAME)) {
			deleteCookie(this.COOKIE_NAME);
		}

		if(couponCode == undefined || couponCode == null) {
			window.location.href = url;
		}
		else {
			addCookie(this.COOKIE_NAME, couponCode);
			window.location.href = url;
		}
}
});
/*--------------------------------------------------------------------------*
 * 
 * Start on document load
 * 
 *--------------------------------------------------------------------------*/
Event.observe(document, 'dom:loaded', function(){
	try {
		//Create instance of class
		new urlCoupon();
	}
	catch(error){/*Ignore*/}
});
