var CouponsPage = new Class({
	initialize: function ( containerId, coupons, couponOrder, selectedCoupons, featuredContainerId, featuredCouponIds, unavailableCoupons, local, numCouponsPerRow, selectAll ){
		this.local = local;
		/**** Regular Coupons ****/
		this.containerId		= containerId;					// Div in which regular coupons will be displayed
		this.coupons 			= coupons.slice();
		this.couponOrder		= couponOrder;
		this.heroContainerId 	= "";
		this.heroCoupons		= new Array();
		
		
		
		this.unavailableCoupons = unavailableCoupons;

		this.numCouponsPerRow	= numCouponsPerRow;
		this.numCouponRows		= Math.ceil( ( this.couponOrder.length + this.unavailableCoupons.length ) / this.numCouponsPerRow );
		this.couponPage;
		this.couponHeroPage;
		
		/**** Featured Coupons ****/
		this.featuredContainerId 		= featuredContainerId; 	// Div in which featured coupons will be placed
		this.featuredCouponIds			= featuredCouponIds;
		this.featuredCoupons			= new Array();			// Coupons that are featured
		this.numFeaturedCouponRows 		= 0;
		this.numFeaturedCouponsPerRow 	= 2;
		
		/*** Hero Coupons ***/

		// Already selected Coupons
		this.selectedCoupons = selectedCoupons;	
		if ( selectAll == true ){
			for ( i = 0; i < this.couponOrder.length; i++ ){
				check = false;
				for ( j = 0; j < this.selectedCoupons.length; j++ ){	
					if ( this.selectedCoupons[j].id == this.coupons[this.couponOrder[i]].id ){
						check = true;	
						break;
					}
				}
				if ( check == false ){
					this.selectedCoupons.push( this.coupons[this.couponOrder[i]] );	
				}
			}
			//this.selectedCoupons = coupons.slice(0);	
		}
		
		for ( i = 0; i < this.unavailableCoupons.length; i++ ){
			for ( j = 0; j < this.selectedCoupons.length; j++ ){
				if ( this.selectedCoupons[j].id == this.unavailableCoupons[i].id ){
					this.selectedCoupons.splice( j, 1 );
					break;
				}
			}
		}
		this.updateSelectedCouponSession();

		// Sliding in and out of Featured Coupons Container
		this.slideFx = new Fx.Slide( this.featuredContainerId );
		$( this.featuredContainerId ).setStyle( 'margin', '0px auto 0px auto' );
		this.firstPageLoad = true;	
		
		/***** Overlay ****/
		var opt = {
			valign          : 'middle',
			halign          : 'middle',
			color           : 'white',
			overlay_opacity : .80,
			duration_in     : 300,
			duration_out    : 150	
		};
		this.overlay = new xOverlayControl( opt ).setOverlay( { 
			'id':'main_overlay', 
			'class':'nooverlayclass' 
		}).setContent({
			'id': 'overlay_container',
			'html': '<div id="overlay_content" style="position:relative"><img id="back_shadow" src="/images/coupon_images/coupons_large_en_ca/back_shadow.png"/><div style="position:absolute; left:13px; top:14px;"><img id="coupon_overlay_image" src="" /></div><div style="position:absolute;top:0px;left:0px"><img src="/images/btn_closeDIVS.gif" id="close_coupon_overlay"/></div></div>'
		}).setLoadingImage('/images/ajax-loader.gif');

		//Initialize page coupons and page elements 
		this.initializeCoupons();
		this.populateCouponPage();
		//
		
		this.createMainCouponDiv();
		this.insertCouponDivs();
	},
	
	// Check for selected coupons
	initializeCoupons: function() {
		this.couponsValue = 0;
		this.featuredCoupons = new Array();
		// Initialzie main coupons
		for ( i = 0; i < this.couponOrder.length; i++ ){			
			// Reset coupon
			this.coupons[ this.couponOrder[i] ].featuredCoupon = null;
			this.coupons[ this.couponOrder[i] ].unSelectCoupon();
			
			for ( j = 0; j < this.featuredCouponIds.length; j++ ){
				if ( this.featuredCouponIds[j] == this.couponOrder[i] ){
					var featuredCoupon = new FeaturedCoupon( this.coupons[ this.couponOrder[i] ] ); 
					featuredCoupon.info_button.set('src','/'+this.local+'/coupons/images/plusinfo.gif');
					featuredCoupon.info_button.set('width','47');
					featuredCoupon.info_button.set('height','9');
					this.featuredCoupons.push( featuredCoupon );	
					this.coupons[ this.couponOrder[i] ].addFeaturedCoupon( featuredCoupon );
				}
			}			
			// Add click event to coupon
			this.coupons[ this.couponOrder[i] ].addClickEvent( this );
			
			
			
			// Check if coupon is in selected coupons array
			for ( j = 0; j < this.selectedCoupons.length; j++ ){
				if ( this.coupons[ this.couponOrder[i] ].id == this.selectedCoupons[j].id ){
					this.coupons[ this.couponOrder[i] ].selectCoupon();
				}
			}
		}

	},
	
	// Fill couponPages array with coupons
	populateCouponPage: function(){
		// Fill couponPage array using the couponOrder and the coupons array.
		this.couponPage = new Array();
		for ( i = 0; i < this.couponOrder.length; i++ ){
			this.couponPage[i] = this.coupons[ this.couponOrder[i] ];	
		}
		// Append the unavailable coupons to the couponPage array
		var length = this.couponPage.length;
		for ( i = 0; i < this.unavailableCoupons.length; i++ ){
			this.couponPage[ length + i ] = this.unavailableCoupons[i];
		}
	},
	
	// Create main structure for holding coupons
	createMainCouponDiv: function(){	
		// main coupon section
		var container_coupons = new Element('div', {
			'id': 'container_coupons'
		}).injectInside( $( this.containerId ) );
		
		var claim_button = new Element( 'div', {
			'id':	'get_my_coupons',
			'html' :'<a class="get_my_coupons_link" href="/'+this.local+'/coupons/login.php" ><img id="get_my_coupons_img" class="next_page_button" src="/'+this.local+'/includes/images/btn_getCoupons.jpg" alt="get_my_coupons"/></a>'
		}).injectInside( $( 'container_coupons' ) );
		
		// Create coupon holder divs in main coupon section
		for ( i = 0; i < this.numCouponRows; i++ ){		
			var coupon_row = new Element( 'div', {
				'id': 	'coupon_row_' + i,
				'class':'coupon_row'
			}).injectInside( $('container_coupons') );
			
			for ( j = 0; j < this.numCouponsPerRow; j++ ){
				var coupon_holder = new Element('div',{
					'id':	'coupon_holder_' + (i*this.numCouponsPerRow + j),
					'class':'coupon_holder'											
				}).injectInside( coupon_row );
			}
			var clear_div = new Element( 'div', {
				'style': 'clear:both'							
			}).injectInside( coupon_row );
		}
		if ( this.featuredCoupons != null ) this.createFeaturedCouponDiv();		
		
		// Another claim coupons button
		var claim_button2 = new Element( 'div', {
			'id': 	'submit',
			'html': '<a class="get_my_coupons_link" href="/'+this.local+'/coupons/login.php" ><img id="claim_button_img" class="next_page_button" src="/'+this.local+'/includes/images/btn_getCoupons.jpg" /></a>'
		}).injectInside( $( 'container_coupons' ) );
		
		$('num_coupons').set('html', this.selectedCoupons.length );
		$('coupons_value').set('html', '$' + this.selectedCouponsValue().toFixed(2) );
	},
	
	// Create and fill div that holds the featured coupons 
	createFeaturedCouponDiv: function(){
		// Set number of featured coupon rows
		if ( this.featuredCoupons.length < 2 ) this.numFeaturedCouponRows = 0;
		else if ( this.featuredCoupons.length >= 2 && this.featuredCoupons.length < 4  ) this.numFeaturedCouponRows = 1;	
		else if ( this.featuredCoupons.length >= 4 ) this.numFeaturedCouponRows = 2;	
		
		// Create and fill featured coupon section
		$( this.featuredContainerId ).empty();
		for ( i = 0; i < this.numFeaturedCouponRows; i++ ){
			var coupon_row = new Element( 'div', {
				'id' : 'coupon_row_featured_' + i,
				'class' : 'coupon_row_featured'
			}).injectInside( this.featuredContainerId );
			
			for ( j = 0; j < this.numFeaturedCouponsPerRow; j++ ){
				var coupon_holder = new Element('div', {
					'id': 'coupon_holder_featured_' + (i*this.numFeaturedCouponsPerRow + j),
					'class': 'coupon_holder_featured'											
				}).injectInside( coupon_row );
				( this.featuredCoupons[i*this.numFeaturedCouponsPerRow + j].couponDiv ).injectInside( coupon_holder );			
			}
			
			var clear_div = new Element( 'div', {
				'style': 'clear:both'
			}).injectInside( coupon_row );			
		}
		
		// Hack for featured coupons sliding div
		if ( this.numFeaturedCouponRows > 0 && !this.firstPageLoad ){
			$( this.featuredContainerId ).setStyle('display', 'block');
			this.slideFx.slideIn();
		} else if ( !this.firstPageLoad ) {
			this.slideFx.slideOut();
		} else if ( this.firstPageLoad && this.numFeaturedCouponRows == 0 ){
			$( this.featuredContainerId ).setStyle('display', 'none');	
		}
		this.firstPageLoad = false;
	},

	
	// Insert all coupons from the couponPage array into the page
	insertCouponDivs: function(){
		// Fill regular coupons section
		var j = 0;
		var row = 0;
		$$('.coupon_row').setStyle('display', 'none');
		for ( i = 0; i < this.couponPage.length; i++ ){
			if ( $('coupon_holder_' + i).getFirst() ){
				$('coupon_holder_' + i).getFirst().dispose();	
			}
			if ( this.couponPage[i] != null && this.couponPage[i].featuredCoupon == null ){
				( this.couponPage[i].couponDiv ).injectInside( $('coupon_holder_' + j) );
				if ( j % this.numCouponsPerRow == 0 ){
					$( 'coupon_row_' + row ).setStyle( 'display', 'block' );
					row++;
				}
				j++;
			} 
		}
		// Fill featured coupons section
		for ( i = 0; i < this.numFeaturedCouponsPerRow*this.numFeaturedCouponRows; i++ ){
			if ( $('coupon_holder_featured_' + i).getFirst() ){
				$('coupon_holder_featured_' + i).getFirst().dispose();	
			}
			if ( this.featuredCoupons[i] != null ){
				( this.featuredCoupons[i].couponDiv ).injectInside( $('coupon_holder_featured_' + i) );		
			} 	
		}
					
	},
	
	
	// Re-order coupons
	reorderCoupons: function( couponOrder, featuredCouponIds ){
		//Reset the couponOrder and featuredCouponsIds then reinitialize everything
		this.couponOrder = couponOrder.slice();
		this.featuredCouponIds = featuredCouponIds.slice();
		this.initializeCoupons();
		this.populateCouponPage();
		this.createFeaturedCouponDiv();
		this.insertCouponDivs();
	},
	
	// Add and remove coupons from selected coupons array
	addRemoveSelectedCoupon: function( coupon ){
		isSelected = false;
		for ( i = 0; i < this.selectedCoupons.length; i++ ){
			if ( this.selectedCoupons[i].id == coupon.id ){
				this.selectedCoupons.splice( i, 1 );
				coupon.unSelectCoupon();
				isSelected = true;
				break;
			}
		}
		if ( isSelected == false ){
			this.selectedCoupons.push( coupon );	
			coupon.selectCoupon();
		}
		$('num_coupons').set('html', this.selectedCoupons.length );
		$('coupons_value').set('html', '$' + this.selectedCouponsValue().toFixed(2) );
		
		this.updateSelectedCouponSession();
	},
	
	updateSelectedCouponSession: function(){
		var ref = this;
		var request = new Request({
			method: 	'get',
			url: 		'/php/ajax/update_session.ajax.php',
			data: 		{ 'selected_coupons': this.selectedCouponsToStr() },
			onSuccess: 	function(){},
			onTimeout: 	function(){},
			onException:function(){}
		}).send();
	},
	
	selectedCouponsToStr: function(){
		str = "";
		for ( i = 0; i < this.selectedCoupons.length; i++ ){
			if ( i == this.selectedCoupons.length - 1 ){
				str += this.selectedCoupons[i].id;	
			} else {
				str += this.selectedCoupons[i].id + ", ";
			}
		}
		return str;
	},
	
	selectedCouponsValue: function(){
		value = 0;
		for ( i = 0; i < this.selectedCoupons.length; i++ ){
			value += this.selectedCoupons[i].value;
		}	
		return value;
	},
	
	showOverlay: function( coupon ){
		pageTracker._trackPageview('/coupon-popup/'+coupon.id);
		
		var overlay = this.overlay;
		
		var asset = Asset.image('/images/coupon_images/coupons_large_'+this.local+'/'+coupon.id+'.jpg', {
			'id'	: 'coupon_overlay_image',
			onload 	: function(){						
						overlay.showLoading();				
						overlay.show( null, false );						
					}
		});
		
		$('coupon_overlay_image').set( 'src', '/images/coupon_images/coupons_large_'+this.local+'/'+coupon.id+'.jpg' );

		overlay = this.overlay;
		$('close_coupon_overlay').addEvent( 'click', function(){
			overlay.hide();
			$('close_coupon_overlay').removeEvents();
			$(document).removeEvents();	
		});
		$(document).addEvent('keydown', function(event){
			if ( event.key == 'esc' ){
				overlay.hide();
				$('close_coupon_overlay').removeEvents();
				$(document).removeEvents();
			}
		});
	}	
});

var CouponPageMain = new Class({
	Extends: CouponsPage,
	initialize: function ( containerId, coupons, couponOrder, selectedCoupons, featuredContainerId, featuredCouponIds, heroCoupons, heroContainerId, unavailableCoupons, local, numCouponsPerRow, selectAll ){
		this.local = local;
		/**** Regular Coupons ****/
		this.containerId		= containerId;					// Div in which regular coupons will be displayed
		this.coupons 			= coupons.slice();
		this.couponOrder		= couponOrder;
		
		this.heroContainerId 	= heroContainerId;
		this.heroCoupons		= heroCoupons.slice();
		this.numberHeroCoupons	= this.heroCoupons.length;
		
		
		this.unavailableCoupons = unavailableCoupons;

		this.numCouponsPerRow	= numCouponsPerRow;
		this.numCouponRows		= Math.ceil( ( this.couponOrder.length + this.unavailableCoupons.length ) / this.numCouponsPerRow );
		this.couponPage;
		this.couponHeroPage;
		
		/**** Featured Coupons ****/
		this.featuredContainerId 		= featuredContainerId; 	// Div in which featured coupons will be placed
		this.featuredCouponIds			= featuredCouponIds;
		this.featuredCoupons			= new Array();			// Coupons that are featured
		this.numFeaturedCouponRows 		= 0;
		this.numFeaturedCouponsPerRow 	= 2;
		
		/*** Hero Coupons ***/

		// Already selected Coupons
		this.selectedCoupons = selectedCoupons;	
		if ( selectAll == true ){
			for ( i = 0; i < this.couponOrder.length; i++ ){
				check = false;
				for ( j = 0; j < this.selectedCoupons.length; j++ ){	
					if ( this.selectedCoupons[j].id == this.coupons[this.couponOrder[i]].id ){
						check = true;	
						break;
					}
				}
				if ( check == false ){
					this.selectedCoupons.push( this.coupons[this.couponOrder[i]] );	
				}
			}
			//this.selectedCoupons = coupons.slice(0);	
		}
		
		for ( i = 0; i < this.heroCoupons.length; i++ ){
			check = false;
			for ( j = 0; j < this.selectedCoupons.length; j++ ){	
				if ( this.selectedCoupons[j].id == this.heroCoupons[i].id ){
					check = true;	
					break;
				}
			}
			if ( check == false ){
				this.selectedCoupons.push( this.heroCoupons[i] );	
			}
		}
		
		for ( i = 0; i < this.unavailableCoupons.length; i++ ){
			for ( j = 0; j < this.selectedCoupons.length; j++ ){
				if ( this.selectedCoupons[j].id == this.unavailableCoupons[i].id ){
					this.selectedCoupons.splice( j, 1 );
					break;
				}
			}
		}
		this.updateSelectedCouponSession();

		// Sliding in and out of Featured Coupons Container
		this.slideFx = new Fx.Slide( this.featuredContainerId );
		$( this.featuredContainerId ).setStyle( 'margin', '0px auto 0px auto' );
		this.firstPageLoad = true;	
		
		/***** Overlay ****/
		var opt = {
			valign          : 'middle',
			halign          : 'middle',
			color           : 'white',
			overlay_opacity : .80,
			duration_in     : 300,
			duration_out    : 150	
		};
		this.overlay = new xOverlayControl( opt ).setOverlay( { 
			'id':'main_overlay', 
			'class':'nooverlayclass' 
		}).setContent({
			'id': 'overlay_container',
			'html': '<div id="overlay_content" style="position:relative"><img id="back_shadow" src="/images/coupon_images/coupons_large_en_ca/back_shadow.png"/><div style="position:absolute; left:13px; top:14px;"><img id="coupon_overlay_image" src="" /></div><div style="position:absolute;top:0px;left:0px"><img src="/images/btn_closeDIVS.gif" id="close_coupon_overlay"/></div></div>'
		}).setLoadingImage('/images/ajax-loader.gif');

		//Initialize page coupons and page elements 
		this.initializeCoupons();
		this.populateCouponPage();
		

		
		this.createMainCouponDiv();
		this.insertCouponDivs();
		this.createHeroDiv();
	},
	populateCouponPage: function(){
		// Fill couponPage array using the couponOrder and the coupons array.
		this.couponPage = new Array();
		this.couponHeroPage = new Array();
		for ( i = 0; i < this.couponOrder.length; i++ ){
			this.couponPage[i] = this.coupons[ this.couponOrder[i] ];	
		}
		for ( i = 0; i < this.heroCoupons.length; i++ ){
			this.couponHeroPage[i] = this.heroCoupons[ i ];	
		}
		// Append the unavailable coupons to the couponPage array
		var length = this.couponPage.length;
		for ( i = 0; i < this.unavailableCoupons.length; i++ ){
			this.couponPage[ length + i ] = this.unavailableCoupons[i];
		}
	},
	initializeCoupons: function() {
		this.couponsValue = 0;
		this.featuredCoupons = new Array();
		// Initialzie main coupons
		for ( i = 0; i < this.couponOrder.length; i++ ){			
			// Reset coupon
			this.coupons[ this.couponOrder[i] ].featuredCoupon = null;
			this.coupons[ this.couponOrder[i] ].unSelectCoupon();
			
			for ( j = 0; j < this.featuredCouponIds.length; j++ ){
				if ( this.featuredCouponIds[j] == this.couponOrder[i] ){
					var featuredCoupon = new FeaturedCoupon( this.coupons[ this.couponOrder[i] ] ); 
					featuredCoupon.info_button.set('src','/'+this.local+'/coupons/images/plusinfo.gif');
					featuredCoupon.info_button.set('width','47');
					featuredCoupon.info_button.set('height','9');
					this.featuredCoupons.push( featuredCoupon );	
					this.coupons[ this.couponOrder[i] ].addFeaturedCoupon( featuredCoupon );
				}
			}			
			// Add click event to coupon
			this.coupons[ this.couponOrder[i] ].addClickEvent( this );
			
			
			
			// Check if coupon is in selected coupons array
			for ( j = 0; j < this.selectedCoupons.length; j++ ){
				if ( this.coupons[ this.couponOrder[i] ].id == this.selectedCoupons[j].id ){
					this.coupons[ this.couponOrder[i] ].selectCoupon();
				}
			}
		}
		
		for (i = 0; i < this.heroCoupons.length; i++) {
			this.heroCoupons[ i ].unSelectCoupon();
			this.heroCoupons[ i ].addClickEvent( this );
			for ( j = 0; j < this.selectedCoupons.length; j++ ){
				if ( this.heroCoupons[ i ].id == this.selectedCoupons[j].id ){
					this.heroCoupons[ i ].selectCoupon();
				}
			}
		}

	},	
	createHeroDiv: function(){
		if(this.numberHeroCoupons == 1){
			heroClass = 'coupon_row_hero';
			heroHolderClass = 'coupon_holder_hero';
		} else if( this.numberHeroCoupons < 3 ){
			heroClass = 'coupon_row_featured'; 
			heroHolderClass = 'coupon_holder_featured';
		} else {
			heroClass = 'coupon_row';
			heroHolderClass = 'coupon_holder';
		}
		
		var coupon_row = new Element( 'div', {
				'id':'hero_coupon_div',
				'class': heroClass,
				'style':'display:none'
		}).injectInside( $(this.heroContainerId) );
		
		for( i=0;i<this.numberHeroCoupons;i++ ){
			var coupon_holder = new Element('div',{
				'id':	'coupon_hero_holder_' + i,
				'class': heroHolderClass											
			}).injectInside( coupon_row );
		}
		
		var clear_div = new Element( 'div', {
			'style': 'clear:both'							
		}).injectInside( $(this.heroContainerId) );
		
		for (i = 0; i < this.couponHeroPage.length; i++) {
			( this.couponHeroPage[i].couponDiv ).injectInside( $('coupon_hero_holder_'+ i ) );
			//alert( this.couponHeroPage[i].couponDiv );
		}
		if(this.couponHeroPage.length > 0){
			$('hero_coupon_div').setStyle('display','block');
		}
	}
});

var hero_coupon_error = function(){
	alert('no coupon left');
}

