﻿/// <reference path="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js" />
var selectedInput = null;
var ac            = null;

$(document).ready(function(){
    // voting
    //    $("#vote-yes-button").removeAttr("disabled");
    //    $("#vote-no-button").removeAttr("disabled");
    $(".voteButton").removeAttr("disabled");
    // external popups
    $('A[rel="external"]').click(function(){
        window.open($(this).attr('href'), null, "height=600,width=800,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes");
        return false;
    });
    // highlight first non-search field in page
    //$('form:eq(1) *:input[type!=hidden]:first').focus();
    //$('form:last *:input[type!=hidden]:first').focus();
    $('form:eq(0) *:input[type=text]:first').focus();
    // determine which field has the current focus so that can paste special characters into it
    $('input, textarea').focus(function(){
        //alert(this.id);
        selectedInput = $(this);
    });
    // don't hide the autocomplete div if it was the charmap icon that was clicked
    $(".simple_popup").click(function(){
        clearTimeout(acTimeout);
    });
    // don't hide the autocomplete div if it was anything in the charmap div that was clicked
    //$(".simple_popup_info").click(function(){
    $(".charmapDiv").click(function(){
        clearTimeout(acTimeout);
    });

    //$(".with-date-picker").datepicker();

    // add drag and drop functionality
    $("#charmap").easydrag();

    // disable clicking in the comment field from triggering a row click
    //$(".commentta").click(function(){
    $(".votingpanel").click(function(){
        return false;
    });

    $("#chkQuery").click(function(){
        if ($(this).attr("checked")){
            $("#chkExtended").attr("disabled", "disabled").attr('checked', false);
        }else{
            $("#chkExtended").removeAttr('disabled');
        }
    });

    $(".searchButton").click(function(){
        // disable autocomplete
        if (ac != null)
            ac.abort();
    });
});

//$("input[@type=submit]").click(function(){
//$("#vote-yes-button").click(function(){
$("button.voteButton").click(function(){
    var div = $(this).parents("div").parents("div");
//    var entryid = jQuery.trim($("#entryid").val());   // worked for single vote display
    var entryid = jQuery.trim(div.children("#entryid").val());
//    var comment = jQuery.trim($("#comment").val());   // worked for single vote display
    var commentdiv = div.children("#form-vote-text");
    var commentta = commentdiv.find("#comment");
    var comment = jQuery.trim(commentta.val());

    var approved = false;
    if (this.id.indexOf("yes") != -1)
        approved = true;

    // single vote display vs table display
    var single = true;
    if ($(".entry-table").length != 0 || $(".vote-table").length != 0)
        single = false;

    var votesfor = 0;
    var votesagainst = 0;
    if (single){
        votesfor = $("#vote-yes-span").text();
        votesagainst = $("#vote-no-span").text();
    }else{
        var tr = div.parents("tr");
        var span = tr.find("#vote-yes-span");
        votesfor = span.text();
    }

//	if (text != ""){
    jQuery.post(
			"/entries/addvote",
			{ entryid: entryid, comment: comment, approved: approved, votesfor: votesfor, votesagainst: votesagainst },
			function(data, textVote){

//				var voteUpdateHtml =  "<tr id=\"status_" + data.object.statusId + "\" class=\"status\">"
//				voteUpdateHtml += "<td class=\"status-image\"><a href=\"/users/" + data.object.userName + "\" title=\"" + data.object.name + "\"><img src=\"http://www.gravatar.com/avatar/" + data.object.gravatarHash + "?s=48&d=identicon\" width=\"48\" height=\"48\" alt=\"" + data.object.name + "\" /></a></td>";
//				voteUpdateHtml += "<td class=\"status-text\"><strong><a href=\"/users/" + data.object.userName + "\" title=\"" + data.object.name + "\">" + data.object.userName + "</a></strong>&nbsp;";
//				voteUpdateHtml += data.object.text;
//				voteUpdateHtml += "<span class=\"time\">&nbsp;<a href=\"/users/" + data.object.userName + "/statuses/" + data.object.statusId + "\">0 sec ago</a></span>";
//				voteUpdateHtml += "</td>";
//				voteUpdateHtml += "</tr>";

//			    var voteUpdateHtml = "<tr class=\"vote\">"
//			    voteUpdateHtml += "<td class=\"vote-text\"><strong></strong>";
//			    voteUpdateHtml += "¡Gracias! 1 point awarded!";
//			    voteUpdateHtml += "<span class=\"vote-time\">&nbsp;</span>";
//			    voteUpdateHtml += "</td>";
//			    voteUpdateHtml += "</tr>";

			    var voteUpdateHtml = "<div class=\"vote\">"
			    voteUpdateHtml += "¡Gracias! 1 point awarded!";
			    voteUpdateHtml += "</div>";

//			    var voteUpdate = $(voteUpdateHtml);	    
////			    voteUpdate.prependTo("#vote-updates");
//			    voteUpdate.prependTo(div.children("#vote-updates"));
			    div.children("#vote-updates").html(voteUpdateHtml);		    

			    // clear the text box
//			    $("#comment").val("");
			    commentta.val("");
			    commentta.attr("disabled", "disabled");

			    // updates voting stats
			    if (single){
//			        $("#vote-yes-span").text(data.object.votesFor);
//			        $("#vote-no-span").text(data.object.votesAgainst);
			        $("#vote-yes-span").text(data.votesFor);
			        $("#vote-no-span").text(data.votesAgainst);			        

			        // disable repeat voting
			        $("#vote-yes-button").attr("disabled", "disabled");
			        $("#vote-no-button").attr("disabled", "disabled");
			    }else{
//			        span.text(data.object.votesFor);
			        span.text(data.votesFor);
			        // not yet setting 'votes against'

			        // disable repeat voting
			        tr.find("#vote-yes-button").attr("disabled", "disabled");
			        tr.find("#vote-no-button").attr("disabled", "disabled");		        
			    }
			},
			"json"
		);
//	}

    return false;
});


// User follow - callback
function FollowSuccess (data, textStatus){
	// remove all possible states from button
	$("#user-follow-button").removeClass("following not-following");
	
	if (data.object.friends){
		$("#user-follow-button").addClass("following");
	}else{
		$("#user-follow-button").addClass("not-following");
	}
}

// User follow - post
$("#user-follow-button").click(function (){
	var userName = $(this).attr("meta:id");

	if ($(this).hasClass("following")){
		jQuery.post(
			"/friend/removefriend",
			{ friendUserName: userName },
			FollowSuccess,
			"json"
		);
	}else{
		jQuery.post(
			"/friend/addfriend",
			{ friendUserName: userName },
			FollowSuccess,
			"json"
		);
	}

	return false;
});


// Friend invite - callback
function FollowInviteSuccess(data, textStatus){
    // remove all possible states from button
    $("#friend-invite-button").removeClass("invited not-invited");
    
    if (data.invitationid){
        $("#friend-invite-button").addClass("invited");
        $("#friend-invite-button").attr("meta:guid", data.invitationid);
    }else{
        $("#friend-invite-button").addClass("not-invited");
    }
}

// Friend invite - post
$("#friend-invite-button").click(function(){

    if ($(this).hasClass("invited")){
        var guid = $(this).attr("meta:guid");
        jQuery.post(
			"/friends/removeinvite",
			{ guid: guid },
			FollowInviteSuccess,
			"json"
		);
    }else{
        var userId = $(this).attr("meta:userid");
        jQuery.post(
			"/friends/addinvite",
			{ userid: userId },
			FollowInviteSuccess,
			"json"
		);
    }

    return false;
});


// Invite accept - post and callback
$(".acceptButton").click(function(){

    var guid = $(this).attr("meta:guid");
    var row = $(this).parent().parent();
    jQuery.post(
		"/friends/acceptinvite",
		{ guid: guid },
		function FollowAcceptSuccess(data, textStatus){
            if (data.success){
                row.remove();
            }
        },
		"json"
	);

    return false;
});


$(function(){
    setAutoComplete("txtQuery", "results", "/search/autocomplete");
});

function onSearch(){
//    var txt = $get('txtQuery');
//    var q = txt.value.trim();
    var txt = $("#txtQuery");
    var q = jQuery.trim(txt.val());    

    if (q.length == 0){
        txt.focus();
        return false;
	}else{
        return true;
    }
}

function navigateUrl(url){
    location.href = url;
}

/************************************************************************************************************
* jQuery extentions
***********************************************************************************************************/
jQuery.fn.extend({
    validate: function(fn){
        ///<summary>Validate the element.</summary>
        ///<param name="fn" optional="true">The validation function.</param>
        ///<returns type="bool" />

        // make sure the calling object exists
        if (this[0] == undefined)
            return true;

        if (fn){
            return this.data("validate", fn);
        }else{
            fn = this.data("validate");
            var ret = true;

            // call the validate function if found
            if (fn)
                ret = fn();

            return ret;
        }
    }
});

/************************************************************************************************************
* Extention Methods
***********************************************************************************************************/
//String.prototype.trim = function(){
//    return this.replace(/^\s*/, "").replace(/\s*$/, "");
//}

/************************************************************************************************************
* YUI Rich Text Editor Configuration
***********************************************************************************************************/
var __editorConfig = {
    mode: "textareas",
    theme: "advanced",
    plugins: "advhr,advimage,advlink,contextmenu,inlinepopups,media,paste,safari,spellchecker,xhtmlxtras",

    theme_advanced_toolbar_location: "top",
    theme_advanced_toolbar_align: "center",
    theme_advanced_statusbar_location: "bottom",
    theme_advanced_resizing_use_cookie: false,
    theme_advanced_resize_horizontal: false,
    theme_advanced_resizing: true,
    theme_advanced_resizing_min_height: 200,

    convert_urls: false,

    gecko_spellcheck: true,
    dialog_type: "modal",

    paste_auto_cleanup_on_paste: true,
    paste_convert_headers_to_strong: true,
    paste_strip_class_attributes: "all"
};

/************************************************************************************************************
* Global Form Policy
***********************************************************************************************************/
// set gloal blur for all fields to hide message when not in focus anymore
$("form .field :input").blur(function(){ HideMessage(this); });

// set global submit for forms to call validation event
//$("form").submit(function(){
// set submit for only the comment forms to call the validation event
// for post forms, see manage-posts.js
$("form.comment-create").submit(function(){
    return validateFormSubmit($(this));
});

function validateFormSubmit(form){
    var valid = form.validate();

    // if the form didn't validate then focus the input on the first error
    if (!valid)
        form.find(":input[error]:first").focus();

    return valid;
}

/************************************************************************************************************
* Form Validation
***********************************************************************************************************/
function DisplayMessage(display, input, css, text){
    var message = $(input).parent().children("span.input-message");

    // clear all old css
    message.removeClass("input-info input-error");

    if (display){
        if (css == "input-error"){
            message.data("error", text);
            $(input).attr("error", "true");
        }

        message.text(text);
        message.addClass(css);
    }else{
        // remove the attribute the error isn't 
        // being displayed any more
        if (css == "input-error"){
            message.removeData("error");
            $(input).removeAttr("error");
        }

        // if the error attribute is still present then display
        // the error message else clear out the text
        if (message.data("error") != undefined && message.data("error") != ""){
            message.text(message.data("error"));
            message.addClass("input-error");
        }else{
            message.text("");
        }
    }
}

function DisplayError(display, input, message){
    DisplayMessage(display, input, "input-error", message);
}

function ShowMessage(input, message){
    DisplayMessage(true, input, "input-info", message);
}

function HideMessage(input){
    DisplayMessage(false, input, "input-info", "");
}

function VerifyRequiredField(input, message, originalValue){
    if (originalValue == undefined)
        originalValue = "";

    var valid = jQuery.trim($(input).val()) != jQuery.trim(originalValue);

    DisplayError(!valid, input, message);
    
    return valid;
}

function VerifyEmail(input, message){
    return VerifyRegularExpression("([\\w-]+(?:\\.[\\w-]+)*@(?:[\\w-]+\\.)+[a-zA-Z]{2,7})", input, message);
}

function VerifyInternetAddress(input, message){
    return VerifyRegularExpression("((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s\"]*))", input, message);
}

function VerifyRegularExpression(exp, input, message){
    var process = new RegExp(exp, "i");
    var match = process.exec($(input).val());
    var valid = match != undefined && match.length > 0;

    DisplayError(!valid, input, message);

    return valid;
}

function VerifyMatch(input1, input2, message){
    var valid = $(input1).val() == $(input2).val();

    DisplayError(!valid, input2, message);

    return valid;
}

function VerifyLength(input, rangeStart, rangeEnd, message){
    var valid = $(input).val().length >= rangeStart && $(input).val().length <= rangeEnd;

    DisplayError(!valid, input, message);

    return valid;
}