/**
 * mahalo3.js
 *
 * Generic javascript used globally throught Mahalo three.
 *
 * Copyright (c) 2009 Mahalo.com, Inc
 *
 */
 
$(document).ready(function (e) {
    $("#top-search-box").focus(); 
    // Set global options for all ajax requests
    // These can be overridden in each request if needed
    $.ajaxSetup({
        type: "POST",
        dataType: "json",
        timeout: 120000,
        error: function(xhr, msg, thrownError){
            if( xhr.status > 0  )
                on_ajax_request_error("Something went wrong completing your request. (" + msg + " : " + xhr.status + ")");
        }
    });

    fuzzyTime();
    init_actionbar();

    var next = window.location.href;
    $("#twitter_login").click(function (event) {
        event.preventDefault();
        twitter_getAuthUrl(next);
    });
});

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

function scaleImages(){
	var container = $(".large-crop");
	
    $( ".large-crop .scale-image").each(function(){
        if (!$(this).hasClass('processed')){
    		var w = Math.ceil( $(this).width() / $(this).height() * container.height() );
    		var h = Math.ceil( $(this).height() / $(this).width() * container.width() );
    		if (w < h) {
    			$(this).css({ height: 'auto', width: container.width(), marginTop: -(h-container.height())/2 });
    		    $(this).addClass("processed");
    		} else {
    			$(this).css({ width: 'auto', height: container.height(), marginLeft: -(w-container.width())/2 });
    		    $(this).addClass("processed");
    		}		
        }
    });
}

function fuzzyTime() {
	var now = new Date();
	var now_ms = now.getTime();
	var offset = now.getTimezoneOffset();
	offset = offset * 60 * 1000;
	
	$(".fuzzy").each(function () {
		var timeString = $(this).attr("timestamp");
		
		if (!timeString) {
			return;
		}
		
		var year = timeString.substring(0,4);
		var month = timeString.substring(4,6);
		var day = timeString.substring(6,8);
		var hour = timeString.substring(8,10);
		var minute = timeString.substring(10,12);
		var second = timeString.substring(12,14);
		
		var newDate = new Date();
		newDate.setFullYear(year);
		newDate.setMonth(month - 1);
		newDate.setDate(day);
		newDate.setHours(hour);
		newDate.setMinutes(minute);
		newDate.setSeconds(second);
		
		var ms = newDate.getTime();
		ms -= offset;
		newDate.setTime(ms);
		
		var difference = now_ms - newDate.getTime();
		var dateString = "";
		
		if (difference >= (1000 * 60 * 60 * 24 * 60)) {
			dateString = newDate.toDateString()
		}
		else if (difference >= (1000 * 60 * 60 * 24)) {
			var days = Math.floor(difference / (1000 * 60 * 60 * 24));
			dateString = days + " day";
			if (days != 1) dateString += "s"
			dateString += " ago";
		}
		else if (difference >= (1000 * 60 * 60)) {
			var hours = Math.floor(difference / (1000 * 60 * 60));
			dateString = hours + " hour";
			if (hours != 1) dateString += "s";
			dateString += " ago";
		}
/*		else if (difference < 0) {
			dateString = "In the future.";
		}
*/		else {
			var minutes = Math.floor(difference / (1000 * 60));
			
			if (minutes < 1) {
				dateString = "Less than a minute ago";
			}
			else {
				dateString = minutes + " minute";
				if (minutes != 1) dateString += "s";
				dateString += " ago";
			}
		}
		
		$(this).html(dateString);
	});
}

function confirmation(msg, container, width, dontScroll) {
	$(".msgbox").hide();
	
	if (typeof msg != 'undefined') {
		if (typeof container != 'undefined') {
			var containers = [container];
		}
		else {
			var containers = ["message-container","content-left", "content"];
		}
		
		for (var i = 0; i < containers.length; i++) {
			if ($("#"+containers[i]).length) {
				var offset = $("#"+containers[i]).offset().top - 10;
				
				if (typeof width == 'undefined') {
					var width = 428;
				}
				
			    var html = "<div class='msgbox ui-widget' style='width:" + width + "px;margin: 0 auto;'>";
			    html += '<div class="ui-state-highlight ui-corner-all" style="margin-bottom: 20px; padding: 0 .7em .7em; .7em">';
                html += '<p><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>' + msg +'</p>';
			    html += '</div></div>';

				$(html).prependTo("#"+containers[i]).show();
				
				break;
			}
		}
		
	}
}

function error(msg, container, width, doScroll) {
	$(".msgbox").hide();
	
	if (typeof msg != 'undefined') {

		if (typeof container != 'undefined') {
			var containers = [container];
		}
		else {
			var containers = ["message-container","content-left", "content"];
		}
		
		for (var i = 0; i < containers.length; i++) {
			if (document.getElementById(containers[i])) {
				var container = $("#"+containers[i]);
				
				var offset = container.offset().top - 10;
				
				if (typeof width == 'undefined') {
					var width = 428;
				}

			    var html = "<div class='msgbox ui-widget' style='width:" + width + "px;margin: 0 auto;'>";
			    html += '<div class="ui-state-error ui-corner-all" style="margin-bottom: 20px; padding: 0 .7em .7em; .7em">';
                html += '<p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>' + msg +'</p>';
			    html += '</div></div>';
				
				$(html).prependTo(container).show();
				
				if(doScroll)
				    $('html,body').animate({scrollTop: offset-10}, 1000);	
				break;
			}
		}
	}
}

function on_ajax_request_error(msg){
    var error_msg_suffix = "<br />Please try again or <a href='mailto:contact@mahalo.com' >contact us</a> if you continue to see this message.";
    msg += error_msg_suffix;
    
    error(msg, "content", "450", true);
}

//Functions for templates
function doSectionCancel(section, type, template_id){
    var args = [{ "name":"section_id", "value": section }, { "name":"type", "value": type }, {"name": "template_id", "value": template_id}].concat(API_KEYS);

    $.ajax({
        url: API_URL + "/guides/section_templates/remove/",
        data: args,
        success: function(data){
            if (data.status == false) {
                error(data.msg);
            }
            else {
               document.location.reload(true);
               $('#add-guidenote-select').removeAttr("disabled");
               $('#add-links-select').removeAttr("disabled");
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong removing this section. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function doEditingCancel(){
    $("#edit_section_contents").html("");
    $("#add-section").animate({opacity: "1"}, 1200);
    $('#add-guidenote-select').removeAttr("disabled");
    $('#add-links-select').removeAttr("disabled");
}

function textCounter(field, cntfield, maxlimit, justCount) {
    if (justCount) {
        cntfield.html(field.value.length);
    }
    else {
        if (field.value.length > maxlimit) {
            field.value = field.value.substring(0, maxlimit);
        }
        else {
            var total = maxlimit - field.value.length;
            if( cntfield ){
                cntfield.html(total);
            }
        }
    }
}

function init_actionbar() {
    var path = document.location.href.split("//")[1];
    
    var path = path.substring(path.indexOf("/"));
    
    $("a.nextpage").each(function () {
        var new_href = $(this).attr("href") + "?next=" + path;
        
        $(this).attr("href", new_href);
    });
}

function pageview(views) {
	var viewsToday = views - startOfDayViews;
	
	var viewString = " (" + views + " view";
	if (views != 1) viewString += "s";
	viewString += ")";
	
	// $("#pageviews").html(viewString);
	
	if (viewsToday <= 500 && viewsToday % 20 == 0) {
		if (viewsToday < 500) {
			confirmation("You just viewed your "+viewsToday+"th page today and earned 1 point.<br />You get 1 point for every 20 pages you view up to 500 pages in a day.");
		}
		else {
			confirmation("Wow, you just viewed your 500th page today and earned 1 point.");
		}

        var args = [ {"name": "action", "value": "pageviews" }, {"name": "meta_id", "value": viewsToday }].concat(API_KEYS);

        $.ajax({
            url: API_URL + "/answers/award_points/?callback=?",
            data: args,
            success: function(data){
            },
            error: function(xhr, msg, thrownError){
            }
        });
	}
}

/*********************************
Facebook Connect generic methods

login_callback() should be defined
on a per-page case as different
pages/user-interactions may have
different post-login procedures

**********************************/
var facebookReturnData = null;
    
function facebook_onlogin() {
    $("#facebook-loading").show();

    var args = [];
    $.ajax({
        url: API_URL + "/facebook_login/",
        data: args,
        success: function(data){
            if (data.status == false) {
                $("#facebook-loading").hide();
                error(data.msg);
            }
            else {
                if ("lguserid" in data.login) {
                    
                    // try to call login_callback if it's defined, otherwise,
                    // reload the page.
                    if(typeof login_callback === 'function'){
                        login_callback(data);
                    }
                    else {
                        window.location.reload();
                    }
                }
                else {
                    facebookReturnData = data;

                    // Link with Mahalo account?
                    linkFacebookAndMahalo();
                }
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong logging in with your Facebook account. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function noMahaloAccount() {
    var args = [ {"name": "no_mahalo_account", "value": true } ];
    
    $.ajax({
        url: API_URL + "/facebook_login/",
        data: args,
        success: function(data){
            if (data.status == false) {
                error(data.msg);
            }
            else {
                login_callback(data);
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong logging in with your Facebook account. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function checkMahaloAccount() {
    var username = $("#fb-m-username").val();
    var password = $("#fb-m-password").val();

    var args = [ {"name": "mahalo-username", "value": username }, {"name": "mahalo-password", "value": password }];
    
    $.ajax({
        url: API_URL + "/facebook_login/",
        data: args,
        success: function(data){
            if (data.status == false) {
                error(data.msg, "fb-m-msg", 400, true);
            }
            else {
                login_callback(data);
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong logging in with your Facebook account. (" + msg + " : " + xhr.status + ")");
        }
    });
}

function linkFacebookAndMahalo(data) {
    var html = '<div class="ui-widget-content ui-corner-all" style="padding: 30px 50px 80px 50px; border: 1px solid #666; background: #fff; width: 400px;"><h1>Just one more thing...</h2><br /><div id="fb-m-msg"></div><p>Do you already have a Mahalo account?</p><input type="submit" class="fg-button ui-state-default ui-corner-all" style="margin-top:5px" value="No, just log me in with my Facebook account" onclick="$.modal.close(); noMahaloAccount();" />';
    html += '<input type="submit" class="fg-button ui-state-default ui-corner-all" style="margin-top:5px" value="Yes, link my Facebook account to this Mahalo account" onclick="checkMahaloAccount();" />';
    html += '<div class="half-column"><small id="login-first-label">Username:</small><br /><input class="textedit" type="text" id="fb-m-username" name="uname" value="" style="width: 175px;" /></div>';
    html += '<div class="half-column"><small id="login-second-label">Password:</small><br /><input class="textedit" type="password" id="fb-m-password" name="login-password" value="" style="width: 175px;" /></div>';
    $(html).appendTo($("body")).modal();
}

function twitter_getAuthUrl(next) {
    var args = [{"name": "next", "value": next }];
    
    $.ajax({
        url: API_URL + "/twitter_getAuthUrl/",
        data: args,
        success: function(data){
            if (data.status == false) {
                error(data.msg, "message-container");
            }else {
                document.location.href = data.auth_url;
            }
        },
        error: function(xhr, msg, thrownError){
            on_ajax_request_error("Something went wrong connecting to twitter. (" + msg + " : " + xhr.status + ")");
        }
    });
}
