var COOKIE_PREFIX = "pt_";
var COOKIE_DELIMITER = ':';
var INTERNAL_COOKIE_DELIMITER = '-';
var COOKIE_EXPIRATION = 30;

var PriceTrackerCookies = function() { }


PriceTrackerCookies.get = function(type) {
	var cookie = Cookies.readCookie(COOKIE_PREFIX + type);
	if (cookie != null) {
		var tokens = cookie.split(COOKIE_DELIMITER);
		return tokens;
	}
}

//
// gets tracked price for the supplier of the given type with the given id.
// return value is   [amount left for feedback, departure date, return date]
PriceTrackerCookies.getTrackedPrice = function(type, trackId) {
	var trackedPrices = DealCookies.get(type);
	if (trackedPrices != null)
	{
		for (var i = 0; i < trackedPrices.length; i++)
		{
			var tokens = trackedPrices[i].split(INTERNAL_COOKIE_DELIMITER);
			if (tokens[0] == trackId) {
				return [ tokens[1], Cookies.parseDate(tokens[2]), Cookies.parseDate(tokens[3]) ];
			}
		}
	}
	
	return null;
}

PriceTrackerCookies.setTrackedPrice = function(type, trackId, amount, departureDate, returnDate) {
	var trackedPrices = PriceTrackerCookies.get(type);	
	var output = '';
	if (trackedPrices != null)
	{
		for (var i = 0; i < trackedPrices.length; i++) {
			var tokens = trackedPrices[i].split(INTERNAL_COOKIE_DELIMITER);
			if (tokens[0] != trackId) {
				output += trackedPrices[i];
				output += COOKIE_DELIMITER;
			}
		}
	}
		
	output += trackId;
	output += INTERNAL_COOKIE_DELIMITER;
	output += amount;
	log(output);
	output += INTERNAL_COOKIE_DELIMITER;
	output += Cookies.formatDate(departureDate);
	output += INTERNAL_COOKIE_DELIMITER;
	log("fool");	
	log(returnDate);	
	output += Cookies.formatDate(returnDate);
	log(output);
	Cookies.writeCookie(COOKIE_PREFIX + type, output, COOKIE_EXPIRATION);					
}

sendPriceTrackerEmail = function() {
	doLoading(true,$('emailButton'));
	var msg;
	if ($F('priceEmails').length==0) {
		msg = 'Please enter one or more email addresses.';
		setTimeout("doLoading(false);","500");
	} else {
		var proxy = function(result) {
			msg = result;
			setTimeout("doLoading(false);","500");
			handleTrackerMessage(msg);
		}
		ajax.sendPriceTrackerEmail($F('priceEmails'), {callback:proxy});
	} 
}

sendRealDealToFriend = function() {
	doLoading(true,$('sendRealDealToAFriendButton'));
	if ($('sendRealDealToAFriend').value.length > 0){
		var deal = $('realDealsDealHiddenTitle').innerHTML;
		var proxy = function(result) {
			msg = result;
			setTimeout("doLoading(false);","500");
			$('errorSendDealToAFriend').innerHTML = result;
		}
		
		var subscriber;
		var cookies = getCookies();
		for (var i = 0; i < cookies.length; i++){
			if(cookies[i].key == 'dealcheckersubscriber'){
				subscriber = cookies[i].value+', ';
			}
		}
		ajax.sendRealDealToFriend(subscriber, $('sendRealDealToAFriend').value, deal, {callback:proxy});
		
	}
	else {
		setTimeout("doLoading(false);","500");
		$('errorSendDealToAFriend').innerHTML = 'Please enter one or more email addresses.<br/>';
	}
}

handleTrackerMessage = function(msg) {
	$('emailMessage').innerHTML = msg;
}

clearPriceTracker = function() {
	if (confirm("Are you sure you want to clear your deals?")) {
		$('trackedDealsInner').innerHTML = '';
		Element.hide($('clearPriceTracker'));
		Element.hide($('emailDeals'));
		Element.show($('noDeals'));
		PriceTracker.clearCookie();
		ajax.clearPriceTracker();
	}
}

var PriceTracker = Class.create();
PriceTracker.prototype = {

	type : null,
	supplierId : null,
	supplierName : null,
	supplierDisplay : null,
	stage : null,
	stageIndex : null,
	price : null,
	startDate : null,
	endDate : null,
	priceTracker : null,
	groupTitle : null,

	initialize: function(type, supplierId, supplierName, supplierDisplay, groupTitle, searchId) {
		this.type = type;
		this.supplierId = supplierId;
		this.stageIndex = 1;
		this.stage = "Q1";
		this.supplierName = supplierName;
		log(supplierDisplay);
		this.supplierDisplay = supplierDisplay;
		this.groupTitle = groupTitle;
		this.searchId = searchId;
	},
	
	setStage: function(stage) {
		this.stage = stage;
	},
	
	getResponse: function() {
		log("this.type + this.stage" + this.type + this.stage);
		var result = TrimPath.processDOMTemplate(this.type + this.stage, this.getData(this.stage));
		if (this.stage == 'R1') {
			log("this.stage : R1");
			Element.hide($('noDeals'));
			Element.show($('priceTracker'));
			Element.show($('emailDeals'));
			Element.show($('clearPriceTracker'));
			if ($(this.groupTitle)==null) {
				log("this.type" + this.type);
				var title = TrimPath.processDOMTemplate(this.type + 'GT1', this.getData('GT1'));
				log("title" + title);
				new Insertion.Top($('trackedDealsInner'),title);
			}
			new Effect.Squish($('tracker_' + this.supplierId));
			new Insertion.After($(this.groupTitle),result);
			new Effect.Highlight($('trackRow'),{duration:2.5});
		} else {
			//closeDivsByName('pt');
			Position.clone($('result' + this.supplierId),$('tracker_' + this.supplierId));
			$('tracker_' + this.supplierId).style.width='57%';
			$('result' + this.supplierId).style.height='100%';
			new Effect.Appear($('tracker_' + this.supplierId));
			$('tracker_' + this.supplierId).innerHTML=result;
			$('problemFeedbackLink' + this.supplierId).style.display = 'block';
		}
	},
	
	getData: function(stage) {
		var data = {
			Q1 : { supplierId: this.supplierId, supplierName : this.supplierDisplay },
			Q2 : { supplierId: this.supplierId, price : this.priceTracker },
			R1 : { priceTracker : this.priceTracker, startDate : this.startDate, endDate :  this.endDate, supplierName : this.supplierName, supplierId : this.supplierId},
			GT1 : { groupTitle : this.groupTitle}
		};
		return data;		
	},
	
	trackPrice : function()	{
		log("trackPrice");
		var val = $F('feedback' + this.supplierId);
		log("val" + val);
		this.startDate = $F('startDate');
		this.endDate = $F('endDate');
		if (val != null && val.length > 0 && !isNaN(val)) {
			//ajax.trackPrice($F('departure'), $F('destination'), val, this.startDate, this.endDate, this.supplierId, this.groupTitle, $F('priceEmails'), $F('cabinClass'),{callback:this.priceTracked.bind(this),errorHandler:doNothing});
			log(this.groupTitle + " " + val + " " + this.supplierId + " " + $F('priceEmails') + " " + this.searchId);			
			ajax.trackPrice(this.groupTitle, val, this.supplierId, $F('priceEmails'), this.searchId, {callback:this.priceTracked.bind(this),errorHandler:doNothing});
		} else {
			new Effect.Shake($('feedback' + this.supplierId));
			alert("Please enter a valid price");		
			$('feedback' + this.supplierId).focus();
		}
	},	
	
	getCookieKey : function() {
		return $F('departure') + '|' + $F('destination')+ '|' + this.supplierId;
	},
	
	priceTracked : function(priceTracker) {
		log("priceTracked");
		if (priceTracker!=null) {
			this.priceTracker = priceTracker;
			log("priceTracked");
			//PriceTrackerCookies.setTrackedPrice(this.type, this.getCookieKey(), this.price, Cookies.parseDate(this.startDate), Cookies.parseDate(this.endDate));
			PriceTracker.setCookie(priceTracker.id);
			this.stage = "R1";
			this.getResponse();
			this.stage = "Q1";
		}
	},
	
	handleError : function(error) {
		alert("Error occurred:");
	}
}
