﻿/// <reference path="dummy_files/dummy_businessconstants.js" />
(function($) {

	var ResultsCompare = {

		cookieName: 'Selections',
		webMethod: 'CompanyListings/SetFilterSelection',

		toggleCss: function(checkbox) {
			checkbox.parents('.listing').toggleClass('selected');
		},

		setCookie: function(value) {
			$.cookie(this.cookieName, value, { path: '/' });
		},

		getCookie: function() {
			return $.cookie(this.cookieName);
		},

		length: function(cookie) {
			//$('.listing').hasClass('selected').length;
			var ids = cookie.split(',');
			return ids.length;
		},

		exists: function(cookie, value) {
			if (cookie) {
				var ids = cookie.split(',');
				var i = ids.indexOf(value);
				if (i > -1) {
					return i;
				}
			}

			return -1;
		},

		setSelection: function(checkbox) {
			var cookie = this.getCookie();
			var value = checkbox.value;
			var filter = new QueryStrings(window.location.href).get('filter');
			if (checkbox.checked) {
				// add value to cookie
				if (cookie) {
					if (this.exists(cookie, value) == -1) {
						var ids = cookie.split(',');
						ids.push(value);
						this.setCookie(ids.join(','));
					}
				} else {
					this.setCookie(value);
				}

				if ($('div.selected').length >= 0 && filter == 'true') {
					$('#show_all').hide();
					$('#compare').show();
				}
			}
			else {
				var i = this.exists(cookie, value);
				if (i > -1) {
					var ids = cookie.split(',');
					ids.splice(i, 1);
					this.setCookie(ids.join(','));

					if ($('div.selected').length <= 1 && filter == 'true') {
						$('#show_all').show();
						$('#compare').hide();
					} else {

						//Shows the 'compare' button if a user unchecks a check box
						//Example: select 6, hit compare, show all is shown, now wants to narrow to 4, unchecks 2
						//the compare button is back.  I like it.
						$('#show_all').hide();
						$('#compare').show();
					}
				}
			}



			this.toggleCss($(checkbox));
		},

		setFilter: function() {
			var q = new QueryStrings(window.location.href);
			q.set('page', 1);
			q.set('filter', true);
			window.location = q.toURL();
		},

		clearSelection: function() {
			ResultsCompare.setCookie('');

			var q = new QueryStrings(window.location.href);
			q.set('filter', false);
			window.location = q.toURL();
		},

		setupFilter: function() {
			var cookie = this.getCookie();

			$('.tabs_select :checkbox').each(function() {

				var checkbox = $(this).click(function() {
					ResultsCompare.setSelection(this);
				});

				if (ResultsCompare.exists(cookie, this.value) > -1) {
					this.checked = true;
					ResultsCompare.toggleCss(checkbox);
				}
			});

			$('#show_all').click(function() {
				ResultsCompare.clearSelection();
				return false;
			});

			$('#compare').click(function() {
				if ($('div.selected').length <= 0 )
					ResultsCompare.window.show().dialog('open');
				else
					ResultsCompare.setFilter();
				
				return false;
			});
		},

		setupNoCompare: function() {

			this.window = $('#noCompare').dialog({
				autoOpen: false,
				modal: true,
				stack: true,
				bgiframe: true,
				height: 50,
				width: 200,
				draggable: false,
				overlay: { opacity: 0.5, background: '#000' }
			});

			$('.btn_save a').click(function() {
				// clear out errors
				$('#save_search_errors').hide();
				$('#txtSaveSearchTitle').removeClass(Search.errorTextCss);

				Search.window.show().dialog('open');
				return false;
			});
		},

		init: function() {
			this.setupNoCompare();
			var filter = new QueryStrings(window.location.href).get('filter');

			if (filter == 'true') {
				$('#show_all').show();
				$('#compare').hide();
			} else {
				$('#show_all').hide();
				$('#compare').show();
			}
			this.setupFilter();
		}
	};

	var Search = {

		maxSearchError: 'You\'ve reached the maximum allowed saved searches.',
		window: undefined,
		cookieName: 'searchlist',
		errorTextCss: 'error_form',

		onSave: function() {
			var criteria = {
				title: $('#txtSaveSearchTitle').val(),
				type: $('#hdnSaveSearchType').val(),
				url: $('#hdnSaveSearchSearchUrl').val()
			};

			// get saved objects
			var saved = Search.getSaved();

			// if item exists, update criteria
			var i = saved.length;
			var title = criteria.title.toLowerCase();

			while (i--) {
				if (saved[i].title.toLowerCase() == title) {
					saved[i] = criteria;
					Search.setCookie($.toJSON(saved));
					Search.render();
					Search.window.dialog('close');
					return;
				}
			}

			if (!Search.valid(saved, criteria)) {
				return false;
			}

			// else add the new search to save
			saved.push(criteria);
			Search.setCookie($.toJSON(saved));

			// show saved results and close modal
			Search.render();
			Search.window.dialog('close');
			return false;
		},

		valid: function(cookie, criteria) {

			if (strIsEmpty(criteria.title)) {
				this.error('Name cannot be blank.');
				return false;
			}
			else if (cookie.length == 4) {
				this.error(this.maxSearchError);
				return false;
			}

			// max of two saves per type
			var i = cookie.length, c = 0;
			while (i--) {
				var item = cookie[i];
				if (item.type == criteria.type) {
					c++;
				}
			}

			if (c == 2) {
				this.error(this.maxSearchError);
				return false;
			}

			return true;
		},

		setupModal: function() {

			this.window = $('#save_search_modal').dialog({
				autoOpen: false,
				modal: true,
				bgiframe: true,
				position: ['auto', 175],
				//height: 'auto', //280,
				width: 350,
				draggable: false,
				buttons: {
					Save: this.onSave
				},
				overlay: { opacity: 0.5, background: '#000' }
			});
			//$('#save_search_modal').dialog('center', 'position', $('#save_search_modal').dialog('center', 'position'));

			$('.btn_save a').click(function() {
				// clear out errors
				$('#save_search_errors').hide();
				$('#txtSaveSearchTitle').removeClass(Search.errorTextCss);

				Search.window.show().dialog('open');
				return false;
			});
		},

		error: function(message) {
			$('#save_search_errors').html(message).show();
			$('#txtSaveSearchTitle').addClass(Search.errorTextCss);
		},

		setCookie: function(val) {
			$.cookie(this.cookieName, val, { path: '/', expires: 90 });
		},

		render: function() {
			var savedItems = new StringBuilder();
			var compItems = new StringBuilder();

			var saved = this.getSaved().reverse();
			var i = saved.length;
			while (i--) {
				var item = saved[i];
				if (item.type == 'details') {
					compItems.append('<li><a href=')
                    .append(item.url)
                    .append(' title="')
                    .append(item.title)
                    .append('">')
                    .append(item.title)
                    .append('</a></li>');
				}
				else {
					savedItems.append('<li><a href=')
                    .append(item.url)
                    .append(' title="')
                    .append(item.title)
                    .append('">')
                    .append(item.title)
                    .append('</a></li>');
				}
			}

			$('#companySearches').empty().html(compItems.toString());
			$('#resultsSearches').empty().html(savedItems.toString());
		},

		getSaved: function() {
			var saved = $.cookie(this.cookieName);
			if (strIsEmpty(saved)) {
				saved = '[]';
			}
			return $.evalJSON(saved);
		},

		init: function() {
			this.setupModal();

			var prev = window.preview;
			if (!prev || prev == '0') {
				this.render();
			}
		}
	};

	var BuyerSplit = {
		window: undefined,
		errorTextCss: 'error_form',

		reset: function() {
			$('#form_cost :radio[value=seller]').attr('checked', 'true');
			$('#split_modal :radio').attr('checked', '');
			BuyerSplit.clearError();
		},

		getValues: function() {
			var loan = tryParseFloat($('#split_loan_amount').val());
			var percent = tryParseFloat($(':selected', this.window).val());
			return { loanAmount: loan, criteria: $(':checked', this.window).val(), percent: percent };
		},

		clearError: function() {
			$('#split_modal .error').hide();
			$('#split_loan_amount').val('').removeClass(this.errorTextCss);
		},

		error: function(message) {
			$('.error', this.window).html(message).show();
			$('#split_loan_amount', this.window).addClass(this.errorTextCss);
		},

		onContinue: function() {
			var vals = BuyerSplit.getValues();
			var q = new QueryStrings(window.location.href);

			// we need purchase price in order to continue
			var price = tryParseFloat(q.get('purchasePrice'));
			if (price == 0) {
				price = tryParseFloat($('#hdnPurchasePrice').val());
				if (price == 0) {
					BuyerSplit.error('Purchase price needs to be set in order to display buyer/seller splits');
					return;
				}
			}

			if (strIsEmpty(vals.criteria)) {
				if (vals.loanAmount > 0 && vals.loanAmount <= businessConstants.LoanAmountMax) {
					q.set('loanAmount', vals.loanAmount);
				} else {
					BuyerSplit.error('Please enter a valid loan amount');
					return;
				}
			} else {
				switch (vals.criteria) {
					case 'loan':
						var loan = new Number(price - (price * vals.percent));
						q.set('loanAmount', loan.toFixed(2));
						break;
					case 'cash':
						q.set('loanAmount', 0);
						break;
					default:
						// unknown so assume 20%
						var loan = new Number(price - (price * 0.20));
						q.set('loanAmount', loan.toFixed(2));
						break;
				}
			}

			// set user role
			q.set('Split', 'true');
			window.location = q.toURL();
		},




		init: function() {

			// setup modal
			this.window = $('#split_modal').dialog({
				autoOpen: false,
				modal: true,
				stack: true,
				height: 300,
				width: 340,
				draggable: false,
				close: this.reset,
				buttons: { Continue: this.onContinue },
				overlay: { opacity: 0.5, background: '#000' }
			});

			// clear out loan amount if user selects other options
			$(':radio', this.window).click(function() {
				BuyerSplit.clearError();
			});

			// deselect any of the other options
			$('#split_loan_amount').focus(function() {
				$('#split_modal :radio').attr('checked', '');
			});

			// setup buyer/seller radio buttons
			$('#form_cost :radio').click(function() {
				var q = new QueryStrings(window.location.href);
				if (!strIsEmpty(this.value) && this.value.toLowerCase() == 'both') {
					if (q.get('LoanAmount') > 0 || (q.get('IsAllCashPurchase') != undefined && q.get('IsAllCashPurchase').toLowerCase() == 'true')) {
						q.set('Split', 'true');
						window.location = q.toURL();
					} else {
						BuyerSplit.reset();
						BuyerSplit.window.dialog('open');
					}
				} else {
					q.set('Split', 'false');
					window.location = q.toURL();
				}
			});

			// set the radio button states
			var q = new QueryStrings(window.location.href);
			var split = q.get('Split');
			if (!strIsEmpty(split) && split.toLowerCase() == 'true') {
				$('#form_cost :radio[value=both]').attr('checked', 'true');
			} else {
				$('#form_cost :radio[value=single]').attr('checked', 'true');
			}
			//preventing links in print mode.
			var print = q.get('print');
			if (!strIsEmpty(print) && print.toLowerCase() == 'true')
			    $('.listing_address a').bind('click', function(e){
			        e.preventDefault();
			    });
		}
	};
	
	
	var EmailPrint = {
		emailPrintPrompt : null,
		isReAgentLoggedIn: null,
		pdfCoverLetterUrl: null,
		reAgentId: null,
		promptType: null,
		printHref: null,
		
		setupDialog: function() {
		
			$('#CoverLetterYes').attr("checked", false); 
			$('#CoverLetterNo').attr("checked", false); 
			
			$('#divCoverLetterYes').hide();
			$('#divCoverLetterEmailFields').hide();
			$('.divEmailFields').hide();
			
			if(EmailPrint.isReAgentLoggedIn == "true"){
				if(EmailPrint.promptType == 'email'){
					$('#divPromptForCoverLetter').show();
				}
			} else {
				$('#fldsetCoverLetterPrompt').hide();
				$('#CoverLetterNo').click();
				$('#divCoverLetterYes').hide();
				if(EmailPrint.promptType == 'email'){
					$('.divEmailFields').show();
				}
			}
		},
		
		escapeHTML: function(str){
		   var div = document.createElement('div');
		   var text = document.createTextNode(str);
		   div.appendChild(text);
		   return div.innerHTML;
		},
		
		init: function() {
			EmailPrint.isReAgentLoggedIn = $('#isReAgentLoggedIn').val();
			EmailPrint.reAgentId = $('#reAgentId').val();
			EmailPrint.pdfCoverLetterUrl = $('#pdfCoverLetterUrl').val();
			
			$('#emailLink').bind('click',function() {
				EmailPrint.promptType = 'email';
				$('#emailPrintSend').val('Send');
				$('#clPromptHeading').text('Send an E-mail');
				$('#spnPromptQuestion').html('Would you like to include a cover letter in your e-mail?');
				EmailPrint.setupDialog();
				window.CLValidation.clear();
				EmailPrint.emailPrintPrompt.parents('.ui-dialog').find('.ui-dialog-titlebar').remove();
				EmailPrint.emailPrintPrompt.dialog('open');
				return false;
			});
			
			$('#printLink').bind('click',function() {
				if(EmailPrint.isReAgentLoggedIn == "true"){
					EmailPrint.printHref = $('#printLink').attr('href');
					EmailPrint.promptType = 'print';
					$('#emailPrintSend').val('Print');
					$('#spnPromptQuestion').html('Would you like to include a cover letter?');
					$('#clPromptHeading').text('Print Page');
					EmailPrint.setupDialog();
					window.CLValidation.clear();
					EmailPrint.emailPrintPrompt.parents('.ui-dialog').find('.ui-dialog-titlebar').remove();
					EmailPrint.emailPrintPrompt.dialog('open');
					return false;
				}
			});
			
			$('#emailPrintSend').bind('click',function(e) {
				var includeCoverLetter = $('#CoverLetterYes').is(':checked');
				if(EmailPrint.isReAgentLoggedIn == "false"){
					$('#CoverLetterNo').attr('checked',true);//IE6 workaround
				}
				if(window.CLValidation.validate(includeCoverLetter,EmailPrint.promptType == 'email') == false) {
					e.preventDefault();
					return;
				} 
				if(EmailPrint.promptType == 'print'){
					if(includeCoverLetter){
						
						EmailPrint.pdfCoverLetterUrl = EmailPrint.pdfCoverLetterUrl.replace(/%24preparedBy/,$('#PreparedBy').val());
						EmailPrint.pdfCoverLetterUrl = EmailPrint.pdfCoverLetterUrl.replace(/%24preparedFor/,$('#PreparedFor').val());
						EmailPrint.pdfCoverLetterUrl = EmailPrint.pdfCoverLetterUrl.replace(/%24comments/,$('#CoverLetterYesComments').val());
						EmailPrint.pdfCoverLetterUrl = EmailPrint.pdfCoverLetterUrl.replace(/%24printUrl/,EmailPrint.escapeHTML(EmailPrint.printHref));
						EmailPrint.emailPrintPrompt.dialog('close');
						
						$.popUpWin(EmailPrint.pdfCoverLetterUrl);
						return false;
					} else {
						EmailPrint.emailPrintPrompt.dialog('close');
						return false;
					}
				}
				
			});
			
			$('.close_action').bind('click',function() {
				EmailPrint.emailPrintPrompt.dialog('close');
				return false;
			});
			
			$('#CoverLetterYes').bind('click',function() {
				$('#divCoverLetterYes').show();
				$('.divEmailFields').hide();

				if(EmailPrint.promptType == 'email'){
					$('#divCoverLetterEmailFields').show();
					$('#divEmailComments').show();
				} 
				window.CLValidation.clear();
				
			});
			
			$('#CoverLetterNo').bind('click',function() {
				window.CLValidation.clear();
				if(EmailPrint.promptType == 'email'){
					$('#divCoverLetterYes').hide();
					$('#divCoverLetterEmailFields').hide();
					$('.divEmailFields').show();
				} else {
					EmailPrint.emailPrintPrompt.dialog('close');
					$.popUpWin(EmailPrint.printHref);
				}
			});
			
			
			this.emailPrintPrompt = $('#emailPrintPrompt').dialog({
				autoOpen: false,
				width: 730,
				modal: true,
				draggable: false,
				resizable: false,
				bgiframe: $.browser.msie && $.browser.version=="6.0"
			});
			
			this.emailPrintPrompt.parents('.ui-dialog').find('.ui-dialog-titlebar').remove();
			
			
			
		}
	
	};
	
	$(function() {
		ResultsCompare.init();
		Search.init();
		BuyerSplit.init();
		EmailPrint.init();
		if(window.CLValidation != undefined){
			window.CLValidation.init();
		}

		$('.sortSelect').change(function() {
			var q = new QueryStrings(window.location.href);
			q.set('sortMeth', this.value);
			window.location = q.toURL();
		});

		//IE6 fix for hover overs.
		$('#save_search_modal').bgiframe();
		$('#split_modal').bgiframe();
		$('.tooltip').bgiframe();
		$('.link_tip_icon').hover(
			function() {
				$(this).children('.tooltip').removeClass("hide");
				$(this).children('.tooltip').css('z-index', 5000);
			},
			function() {
				$(this).children('.tooltip').addClass("hide");
				$('.noHide').removeClass('hide');
			}
		)
		.click(function(e) {
			e.preventDefault();
		});
				//IE6 fix for hovers.
		
		$('.link_tip').hover(
			function() {
				$(this).children().removeClass("hide");
				$(this).children('tooltip').css('z-index', 5000);
			},
			function() {
				$(this).children().not('.cashTxt').addClass("hide");
			}
		)
		.click(function(e) {
			e.preventDefault();
		});
		
	});

})(jQuery);