﻿$(document).ready(function() {
    $("#addComment").click(function(e) {
        e.preventDefault();
        ($).getJSON("/JsonHandlers/CommentHandler.aspx", { Text: $('#comment-text').val(), EntryId: $('#contest-entry-id').val() }, comment_callback);
    });

    $(".unblockUI").click(function() {
        $.unblockUI();
    });

    $(".flagTrigger").click(function() {
        $("#flagID").val($(this).attr("FlagID"));
        $("#flagType").val($(this).attr("FlagType"));
        $.blockUI({ message: $('#popupFlag') });
    });

    $(".commentVoteTrigger").click(function() {
        ($).getJSON("/JsonHandlers/CommentVoteHandler.aspx", { CommentID: $(this).attr("commentid") }, flag_callback);
        $(this).parent("span").html("<img src='/images/ThumbsUp1.png' />");
    });

    $(".commentVoteTriggerDelete").click(function() {
        if (confirm("Are you sure you want to delete this comment?")) {
            ($).getJSON("/JsonHandlers/CommentVoteHandler.aspx?delete=1", { CommentID: $(this).attr("commentid") }, reload_page);
        }
    });

    $("#btnFlag").click(function() {
        ($).getJSON("/JsonHandlers/FlagHandler.aspx", { Reason: $('#flagReason').val(), Details: $('#flagDetails').val(), Type: $('#flagType').val(), ID: $('#flagID').val() }, flag_callback);
    });

    $("#dontRegister").click(function() {
        doVote(triggerContestID);
        popupDisable();
    });

    $("#popupContactClose").click(function() {
        $('#triggerVote' + triggerContestID + ' .cancel').click();
        popupDisable();
    });

    $('.star').click(function() {
        var id = $(this).parent('div').attr('contestEntryID');
        var rating = $(this).children('a').attr('title');
        ratingAmount_ = rating;
        //alert('ID:' + id + ' Rating:' + rating);

        if ($.cookie("VoterGUID") != null) {
            doVote(id, $.cookie("VoterGUID"));
        }
        else {
            triggerContestID = $(this).attr("contestEntryID");
            openPopup();
        }
    });

    $(".vote-link").click(function() {
        if ($.cookie("VoterGUID") != null) {
            doVote($(this).attr("contestEntryID"), $.cookie("VoterGUID"));
        }
        else {
            triggerContestID = $(this).attr("contestEntryID");
            openPopup();
        }
    });

    $("#btnDeleteEntry").css("color", "red");
    $("#btnDeleteEntry").click(function() {
        if (confirm('Are you sure you want to delete this entry?'))
            $('#delete').val(1);
        else
            return false;
    });
});


function RetrievePassword()
{


    $.ajax({
        type: "POST",
        url: "/JsonHandlers/RetrievePassword.aspx",
        data: "email=" + $("#txtRetrievePassword").val(),
        success: function(msg) {
            if (msg == "ok") {
                $("#divRetrievePasswordFeedback").html("<span style='color:green'>Your password has been sent to the email address provided.</span>");

                
                setTimeout("$('#divRetrievePassword').hide('slow')", 3000);
                setTimeout("$.unblockUI()", 4000);
                setTimeout("$('#txtRetrievePassword').val('')", 4000);
                setTimeout("$('#divRetrievePasswordFeedback').html('')", 4000);
            }
            else {
                $("#divRetrievePasswordFeedback").html("We were unable to find that email address in our system.");
            }
        }
    });
}





var childtimer;
var childwindow;
var reloadPage = false;
var triggerContestID = "";
var ratingAmount_ = 1;

/* Helper Functions */
function updateVoteCount(id, html) {
    $('#' + id).html(html);
}

var _runClickEvents = true;
function SetStarsLock(groupid, rating) {
    _runClickEvents = false;
    $('#' + groupid + ' .star a').each(function() {
        if ($(this).attr('title') == rating) {
            $(this).parent('div').click();
            LockStars(groupid);
            return false;
        }
    });
    _runClickEvents = true;
}

function LockStars(groupid) {
    $('#' + groupid + ' .star').unbind().removeClass('star_live')
}



/* PageMethod Ajax Calls */
function loadCaptcha(msg, contestEntryID) {
    //PageMethods.GetCaptcha(loadCaptcha_success);
    ($).getJSON('/JsonHandlers/VoteHandler.aspx', { Method: 'GetCaptcha', Message: msg, ContestEntryID: contestEntryID }, loadCaptcha_success);
}
function loadCaptcha_success(data) {
    
    // close any open popups
    $.unblockUI();
    //$('#divCaptcha').remove();

    // show captcha
    var msg = (data.Message == 'undefined' ? '' : data.Message);
    //$('#divCaptcha').html('<div id="captchaMessage">' + data.Message + '</div>Captcha: ' + data.CaptchaQuestion + ':<input type="text" id="txtCaptcha" /><input type="button" value="Submit" onclick="doVote(' + data.ContestEntryID + ');">');
    $.blockUI({ message: '<div id="captchaMessage">' + data.Message + '</div>' + data.CaptchaQuestion + ':<input type="text" id="txtCaptcha" /><input type="button" value="Submit" onclick="doVote(' + data.ContestEntryID + ');"><input type="button" value="Cancel" onclick="$.unblockUI();" />' });
}


function doVote(contestEntryID) {
    if (_runClickEvents) {
        $.unblockUI();

        //make sure its still votable
        if ($("#triggerVote" + contestEntryID).hasClass("vote-link")) {
            // mark vote link 'voted'
            $("#triggerVote" + contestEntryID).removeClass("vote-link").addClass('voted');

            //
            var voterGUID = $.cookie("VoterGUID");
            var captchaAnswer = ($('#txtCaptcha').length > 0 ? $('#txtCaptcha').val() : '');
            var captchaSecret = ($.cookie('CaptchaSecret') != null ? $.cookie('CaptchaSecret') : '');
            ($).getJSON('/JsonHandlers/VoteHandler.aspx', { Method: "Vote", ContestEntryID: contestEntryID, RatingAmount: ratingAmount_, VoterGUID: generateGuid(), CaptchaAnswer: captchaAnswer, CaptchaSecret: captchaSecret }, vote_success);
        }
    }
}

function vote_success(data) {
    if (data.RequireCaptcha == 1) {
        // get captcha code
        loadCaptcha(data.Message, data.ContestEntryID);
        $("#triggerVote" + data.ContestEntryID).removeClass('voted').addClass("vote-link"); // revert vote link
    }
    else {
        updateVoteCount('voteCount' + data.ContestEntryID, voteCountPreText + data.VoteCount + voteCountPostText);
        //$("#voteCount" + data.ContestEntryID).html(voteCountPreText + data.VoteCount + voteCountPostText);

        $("#divVote" + data.ContestEntryID).removeClass("vote-link").addClass('voted');
        $("#divVote" + data.ContestEntryID).html(voteTriggerTextPostVote);

        SetStarsLock("triggerVote" + data.ContestEntryID, ratingAmount_);
    }
}

function launch(newURL, newName, newFeatures, orgName) {
    var remote = open(newURL, newName, newFeatures);
    if (remote.opener == null)
        remote.opener = window;
    remote.opener.name = orgName;
    return remote;
}

function LaunchSharer(shareUrl) {
    myRemote = launch(shareUrl, "remoteWindow", "height=500,width=800", "thisWindow");
}

function HandleOpenerCallback(args) {
    alert(args);
}

function RefreshWhenChildCloses() {
    //alert('checking');
    if (!childwindow || childwindow.closed) {
        /// Do your stuff here....
        clearInterval(childtimer); //stop the timer
        window.location.reload();
    }
}
function LaunchPhoenix(url) {
    childwindow = window.open(url
		, 'phoenix'
		, ';fullscreen=yes, menubar=no, location=no, toolbar=no, resizable=yes');
    childtimer = setInterval('RefreshWhenChildCloses()', 1000);
}

function LoginOrRegisterThenReload() {
    reloadPage = true;
    $("#member-optional").html("")
    popupCenter();
    popupLoad();
}

function LoginOrRegisterThenRedirect(url_) {
    reloadPage = url_;
    $("#member-optional").html("")
    popupCenter();
    popupLoad();
}


$(document).ready(function() {
    $("#uploadForm").ajaxForm({
        beforeSubmit: clearOutput,
        success: writeOutput
    });
});

$().ajaxError(function(ev, opts, xhr, msg, ex) {
    //window.console.error(msg + ': ' + ex);
    alert(msg + ': ' + ex);
});

// pre-submit callback
function clearOutput(a, f, o) {
    $.blockUI({ message: $('#pleaseWait') });
}

// success callback
function writeOutput(data) {
    data = data.replace("<PRE>", "");
    data = data.replace("</PRE>", "");
    data = data.replace("<pre>", "");
    data = data.replace("</pre>", "");

    $.unblockUI();

    var jsonObj = eval('(' + data + ')');

    if (jsonObj.Result == "error") {
        alert(jsonObj.Message);
    }
    else if (jsonObj.Result == "deleted") {
        alert("The entry has been deleted.");
        window.location = jsonObj.RedirectTo;
    }
    else {
        //alert(jsonObj.RedirectTo);
        window.location = jsonObj.RedirectTo;
    }
}

// helper
function objToString(o) {
    var s = '{\n';
    for (var p in o)
        s += '    ' + p + ': ' + o[p] + '\n';
    return s + '}';
}

// helper
function elementToString(n, useRefs) {
    var attr = "", nest = "", a = n.attributes;
    for (var i = 0; a && i < a.length; i++)
        attr += ' ' + a[i].nodeName + '="' + a[i].nodeValue + '"';

    if (n.hasChildNodes == false)
        return "<" + n.nodeName + "\/>";

    for (var i = 0; i < n.childNodes.length; i++) {
        var c = n.childNodes.item(i);
        if (c.nodeType == 1) nest += elementToString(c);
        else if (c.nodeType == 2) attr += " " + c.nodeName + "=\"" + c.nodeValue + "\" ";
        else if (c.nodeType == 3) nest += c.nodeValue;
    }
    var s = "<" + n.nodeName + attr + ">" + nest + "<\/" + n.nodeName + ">";
    return useRefs ? s.replace(/</g, '&lt;').replace(/>/g, '&gt;') : s;
};

function validateRegister() {
    var error = "";
    var alertError = "";
    
    if ($('#txtDisplayNameReg').val().length < 1) {
        error += "<li>Missing username</li>";
        alertError += "Missing username\n"
    }
    if ($('#txtEmailAddressReg').val().length < 1) {
        error += "<li>Missing email</li>";
        alertError += "Missing email\n"
    }
    if ($('#txtPasswordReg').val().length < 1) {
        error += "<li>Missing password</li>";
        alertError += "Missing password\n"
    }
    if ($('#txtPasswordReg').val() != $('#txtPasswordReg2').val()) {
        error += "<li>Passwords don't match</li>";
        alertError += "Passwords don't match\n"
    }

    if (!$("#chkTermsAndConditions").attr("checked")) {
        error += "<li>You must accept the Terms and Conditions and Privacy Policy</li>";
        alertError += "You must accept the Terms and Conditions and Privacy Policy\n"
    }

    // show errors
    if (error.length > 0) {
        $('#register-errors').html('<ul>' + error + '<ul>');

        alert(alertError);
        return false;
    }
    return true;
}
function validateLogin() {
    var error = "";
    if ($('#txtEmailAddressLogin').val().length < 1) {
        error += "<li>Missing email</li>";
    }
    if ($('#txtPasswordLogin').val().length < 1) {
        error += "<li>Missing password</li>";
    }

    // show errors
    if (error.length > 0) {
        $('#register-errors').html('<ul>' + error + '<ul>');
        return false;
    }
    return true;
}

function registration_callback_default(result) {
    if (result.Result == 'ok') {
        if (reloadPage == true) {
            location.reload();
        }
        else if (reloadPage.substring(0, 1) == "/") {
            window.location = reloadPage;
        }
        else {
            doVote(triggerContestID);
            popupDisable();
        }
    }
    else {
        alert(result.Result);
    }
}

function login_callback_default(result) {
    if (result.Result == 'ok') {
        if (reloadPage == true) {
            location.reload();
        }
        else if (reloadPage.substring(0, 1) == "/") {
            window.location = reloadPage;
        }        
        else {
            MarkImages(result.VotedOnImages);
            popupDisable();
            doVote(triggerContestID);
        }
    }
    else {
        alert(result.Result);
    }
}

function MarkImages(votedOnImages) {
    

    //alert(votedOnImages);
    //var votedOnImagesArr = votedOnImages.split(",");

    // votedOnImages = [{EntryID: '', Rating: ''}];
    $(votedOnImages).each(function() {
        var entry = this;
        var curItem = $("#triggerVote" + entry.EntryID);

        // alert(entry.EntryID + " " + entry.Rating);

        if (curItem != null) {
            SetStarsLock("triggerVote" + entry.EntryID, entry.Rating);

            $("#divVote" + entry.EntryID).removeClass("vote-link").addClass('voted');
            $("#triggerVote" + entry.EntryID).removeClass("vote-link").addClass('voted');

            if ($(".star").length == 0) { //check if this a rating type
                $("#triggerVote" + entry.EntryID).html(voteTriggerTextPostVote);
            }
        }
    });
/*
    for (var i = 0; i <= votedOnImagesArr.length; i++) {
        var curItem = $("#triggerVote" + votedOnImagesArr[i]);

        if (curItem != null) {
            $("#triggerVote" + votedOnImagesArr[i]).html(voteTriggerTextPostVote);
            $("#divVote" + votedOnImagesArr[i]).removeClass("vote-link").addClass('voted');
            $("#triggerVote" + votedOnImagesArr[i]).removeClass("vote-link").addClass('voted');

            
            //SetStarsLock("triggerVote" + votedOnImagesArr[i], rating);
            
        }
    }
*/
}

function generateGuid() {
    var result, i, j;
    result = '';
    for (j = 0; j < 32; j++) {
        if (j == 8 || j == 12 || j == 16 || j == 20)
            result = result + '-';
        i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
        result = result + i;
    }
    return result
}


function openPopup() {
    popupCenter();
    popupLoad();
}

function comment_callback(data) {
    $('#comment-text').val("");
    location.reload();
}

function flag_callback(data) {
    $.unblockUI();
}

function reload_page() {
    location.reload();
}

function chooseContestToEnter(createdInToolID_, imageURI_, thumbnailURI_) {
    // replace tokens
    $('.contestEntryOption a').each(function() {
        var url = $(this).attr('href');
        url += "&img=" + imageURI_ + "&thumb=" + thumbnailURI_;
        $(this).attr('href', url);
    });
    $.blockUI({ message: $('#divChooseContestToEnter') });
}


/**
 * DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

function ValidateEmailAddress(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
	}