/**
 * Version: $Id: global.js 640 2012-01-20 20:00:30Z billm $
 */



$(document).ready(function() {
	if ($('#user-nav-login')) {
		$('#user-nav-login').mouseover(function() {
			openLogin();
		});
	}
});

// Choose category for yummy

function yumCat(propid) {
	if (!logged_in) {
		//alert(propid+', false');
		like(propid, 'Default');
		reloadYummies(1000);
		return;
	}
	$.ajax({
		type: "post",
		cache: false,
		timeout: 10000,
		url: "/user/ajax/yumCats/",
		success: function(data){
			var code='';
			var cats=[];
		    var r = new Date();
		    var randID = r.getTime();
		    var randID2 = r.getTime()+123;
			if (data.indexOf('ERROR') == 0) {
				alert(data.replace(/ERROR: /, ''));
			}
			else {
				cats = $.parseJSON(data);
				code = 
					'<p id="yumErr_'+randID+'" style="color:red;display:none;">You must choose or create a list before you can continue.</p>'+
					'<p><label>Choose an existing list for this property</label><br />'+
					'<select name="yumCat" size="1" class="yumCat" id="'+randID+'" onchange="$(\'#'+randID2+'\').val(\'\');">'+
					'<option value="">-- Choose one --</option>'+
					'</select></p>'+
					'<p>-- OR --</p>'+
					'<p><label>Create a new list for this property</label><br />'+
					'<input type="text" name="newYumCat" class="newYumCat" id="'+randID2+'" value="" maxlength="45"  onclick="$(\'#'+randID+'\').val(\'\');" /></p>';
				var win = $('<div></div>').html(code).dialog({
			        title: "Choose Property List",
			        width: 500,
			        position: 'center',
			        modal: true,
					buttons: [{
						text: 'Ok',
						click: function() {
							if (!($('#'+randID).val() || $('#'+randID2).val())) {
								$('#yumErr_'+randID).show();
								return;
							}
							//alert(propid+', "'+$('#'+randID).val()+'"');
							if ($('#'+randID).val())
								like(propid, $('#'+randID).val());
							else
								like(propid, $('#'+randID2).val());

							reloadYummies(1000);
							$(this).dialog('destroy');
						}
					},{
						text: 'Cancel',
						click: function(){
							$(this).dialog('close');
						}
					}],
					open: function(event, ui) {
						if (!cats.length)
							cats[0] = "Default";
						$.each(cats, function(x, cat) {
							$('#'+randID).append('<option value="'+cat+'">'+cat+'</option>');
						});
						
					}
				});
			}
		}
	});
}



// Please Login or Register popup

function reg_login(redir) {
	var login_reg_html = 
		'<p>Please Sign-Up or Login to SAVE your Yucky & Yummy lists.</p>'+
		'<p>&nbsp;</p>'+
		'<p>If you don\'t, when you leave they will be lost... which would be a bummer!</p>';
	
	var win = $('<div></div>').html(login_reg_html).dialog({
        title: "Please Register or Login",
        width: 500,
        position: 'center',
        modal: true,
        buttons: [{
			text: 'Sign Up',
			click: function(){
				$('a.ui-dialog-titlebar-close').hide();
				win.dialog( "option", "closeOnEscape", false );
				if (!redir)
					location = '/user/add/?redir=1';
				else
					location = '/user/add/?redir='+encodeURI(redir);
			}
		}, {
			text: 'Login',
			click: function(){
				$('a.ui-dialog-titlebar-close').hide();
				win.dialog( "option", "closeOnEscape", false );
				$(this).dialog('destroy');
				modalLogin(redir);
				/*
				if (!redir)
					location = '/user/login/?redir=1';
				else
					location = '/user/login/?redir='+encodeURI(redir);
				*/
			}
		}]
	});
	
	if (redir) {
		win.bind( "dialogclose", function(event, ui) {
			location = redir;
		});
	}
}

function modalLogin(redir) {
	if (!redir)
		redir2 = 1;
	else
		redir2 = encodeURI(redir);
		
	var login_html = 
		'<form id="UserLoginForm" method="post" action="/user/login" accept-charset="utf-8">'+
			'<div style="display:none;"><input name="_method" value="POST" type="hidden"></div>'+
			'<div class="input text">'+
				'<label for="UserEmail">Email Address</label><input name="data[User][email]" maxlength="255" id="UserEmail" type="text">'+
			'</div>'+
			'<div class="input password">'+
				'<label for="UserPassword">Password</label><input name="data[User][password]" id="UserPassword" type="password">'+
			'</div>'+
			'<input name="redir" value="'+redir2+'" type="hidden">'+
		'</form>';	
	
	var win = $('<div></div>').html(login_html).dialog({
        title: "Login",
        width: 500,
        position: 'center',
        modal: true,
        buttons: [{
			text: 'Login',
			click: function(){
				$('a.ui-dialog-titlebar-close').hide();
				win.dialog( "option", "closeOnEscape", false );
				$('#UserLoginForm').submit();
			}
		},{
			text: 'Cancel',
			click: function(){
				$(this).dialog('close');
			}
		}]
	});
	
	if (redir) {
		win.bind( "dialogclose", function(event, ui) {
			location = redir;
		});
	}
}

function showReset() {
	$('#user-nav-login-content').hide();
	$('#user-nav-reset-msg').css('visibility', 'hidden');
	$('#user-nav-reset-content').show();
	$('#UserEmailReset').val('');
}
function showLogin() {
	$('#user-nav-reset-content').hide();
	$('#user-nav-reset-msg').css('visibility', 'hidden');
	$('#user-nav-login-content').show();
	$('#UserEmail').val('');
	$('#UserPassword').val('');
}

function resetPass(email) {
	if (!$('#UserEmailReset').val()) {
		$('#user-nav-reset-err').html('Email cannot be blank');
		return false;
	}
	$.ajax({
		type: "post",
		cache: false,
		timeout: 10000,
		url: "/user/ajax/pwResetEmail/",
		data: {
			email: $('#UserEmailReset').val()
		},
		success: function(data){
			if (data.indexOf('ERROR') == 0) {
				$('#user-nav-reset-msg').css('visibility', 'hidden');
				$('#user-nav-reset-err').html(data.replace(/ERROR: /, ''));
			}
			else {
				$('#user-nav-reset-err').html('');
				$('#user-nav-reset-msg').css('visibility', 'visible');
				cats = $.parseJSON(data);
				code = 
					'<p id="yumErr_'+randID+'" style="color:red;display:none;">You must choose or create a list before you can continue.</p>'+
					'<p><label>Choose an existing list for this property</label><br />'+
					'<select name="yumCat" size="1" class="yumCat" id="'+randID+'" onchange="$(\'#newYumCat\').val(\'\');">'+
					'<option value="">-- Choose one --</option>'+
					'</select></p>'+
					'<p>-- OR --</p>'+
					'<p><label>Create a new list for this property</label><br />'+
					'<input type="text" name="newYumCat" class="newYumCat" id="'+randID2+'" value="" maxlength="45"  onclick="$(\'.yumCat\').val(\'\');" /></p>';
				var win = $('<div></div>').html(code).dialog({
			        title: "Choose Property List",
			        width: 500,
			        position: 'center',
			        modal: true,
					buttons: [{
						text: 'Ok',
						click: function() {
							if (!($('#'+randID).val() || $('#'+randID2).val())) {
								$('#yumErr_'+randID).show();
								return;
							}
							//alert(propid+', "'+$('#'+randID).val()+'"');
							if ($('#'+randID).val())
								like(propid, $('#'+randID).val());
							else
								like(propid, $('#'+randID2).val());

							reloadYummies(1000);
							$(this).dialog('destroy');
						}
					},{
						text: 'Cancel',
						click: function(){
							$(this).dialog('close');
						}
					}],
					open: function(event, ui) {
						if (!cats.length)
							cats[0] = "Default";
						$.each(cats, function(x, cat) {
							$('#'+randID).append('<option value="'+cat+'">'+cat+'</option>');
						});
						
					}
				});
			}
		}
	});
}

function closeLogin() {
	$('#user-nav-login').removeClass('user-nav-login-hover');
	$('#UserEmail').val('');
	$('#UserPassword').val('');
	$('#UserEmailReset').val('');
	$('#user-nav-login-content').hide();
	$('#user-nav-reset-content').hide();
	$('#user-nav-login-tab').hide();
}

function openLogin() {
	$('#user-nav-login').addClass('user-nav-login-hover');
	$('#user-nav-reset-content').hide();
	$('#user-nav-login-content').show();
	$('#user-nav-login-tab').show();
	$('#UserEmail').val('');
	$('#UserPassword').val('');
	$('#UserEmailReset').val('');
}


/**
 * Function: mailLink
 *
 * Description:
 * 	Spam proofs an email link
 *
 * Parameters:
 * 	contact - [optional] (string) The link text - If blank, it uses the email address as the link text
 * 	name - (string) The part in front of the @
 * 	host - (string) The part in after the @
 * 	nolink - [optional] (bool) If FALSE, the email address is displayed as text only.
 *
 * Returns:
 * 	null
 */
function mailLink(contact, name, host, nolink){
    if (!contact)
        contact = name + '@' + host;
	if (nolink)
	    document.write(name + '@' + host);
	else
	    document.write('<a href="' + 'mail' + 'to:' + name + '@' + host + '">' + contact + '</a>');
}

/**
 * Function: roundIt
 *
 * Description:
 * 	Rounds a number to the given number of places.
 *
 * Parameters:
 * 	Num - (numeric) The number to round.
 * 	Places - (int) The number of decimal places to round to.
 *
 * Returns:
 * 	(numeric) The rounded number.
 */
function roundIt(Num, Places){
    if (Number(Num) == 'NaN') 
        Num = new Number(0);
    //if (Num == "") return Num;
    if (Places > 0) {
        var Rounder = Math.pow(10, Places);
        var newnum = Math.round(Num * Rounder) / Rounder;
        var amt = new String(newnum);
        var a = amt.split('.', 2);
        var d = a[1];
        if (d == null) 
            d = '00';
        else if (d.length == 1) 
            d = d + '0';
        newnum = a[0] + '.' + d;
        return newnum;
    }
    else 
        return Math.round(Num);
}

function number_format (number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // +      input by: Amirouche
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'
    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    // *    example 13: number_format('1 000,50', 2, '.', ' ');
    // *    returns 13: '100 050.00'
    // Strip all characters but numerical ones.
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}


