var currentSpend = 0;
var swfu;
var feedbackDirty=true;
var questionDirty=true;

$(function() {

    resizePage($(window).width());

    var throbber = $('<img src="/images/throbber22.gif" style="display:none;" /><img src="/images/spinner.gif" style="display:none;" />');
    $('body').append(throbber);
    throbber.remove();

    $('#flash_holder p').animate({ opacity: 1.0 }, 7000)
    .queue(function() {
        $(this).slideUp();
        $(this).dequeue();
    });

//    var slider = $('#slider').slider({
//        range: "min",
//        min: 0,
//        max: 300,
//        slide: function(event, ui) {

//            var includeLeft = event.keyCode != $.ui.keyCode.RIGHT;
//            var includeRight = event.keyCode != $.ui.keyCode.LEFT;
//            SetSliderColour();
//            findNearest(includeLeft, includeRight, ui.value)
//        },
//        change: function(event, ui) {

//            var includeLeft = event.keyCode != $.ui.keyCode.RIGHT;
//            var includeRight = event.keyCode != $.ui.keyCode.LEFT;
//            slider.slider('option', 'value', findNearest(includeLeft, includeRight, ui.value));

//            return false;
//        }
//    });

    $(window).resize(function() {
        resizePage($(this).width());
    });

    $('.dropHolder').hoverIntent({
        sensitivity: 3,
        interval: 0,
        over: function() {
            $(this).children('.dropTrigger').addClass('active');
            $(this).children('.dropDown').slideDown(150);
        },
        timeout: 200,
        out: function() {
            $(this).children('.dropTrigger').removeClass('active');
            $(this).children('.dropDown').slideUp(150);
        }
    });

    $('.actionList').find('a').click(function() {
        var elem = this;
        openAction(this);
        $(elem).parents('.actions').children('.testPrompt').children().css('display', 'none');
        $(elem).parents('.actions').children('.testPrompt').children("'" + $(elem).attr('rel') + "'").css('display', 'block').children('a.close').click(function() { clearAction(elem); return false; });
        return false;
    });

    $('.priorityCurrent').each(function() {
        $(this).css('width', $(this).text());
        var p = parseInt($(this).text().slice(0, -1));
        $(this).css('background', GetSliderRGB(p));
    });

    $('.copyPaste').click(function() {
        this.select();
    });

    $('.tokenCount').click(function() {
        SetSliderPosition($(this).text())
    });

    $('.tokenBox').click(function() {
        $('.tokenBox').removeClass('active');
        $('.tokenBox input').attr('checked', '');
        $(this).addClass('active');
        $(this).children('input').attr('checked', 'checked');
    });

    $('div.option').click(function() {
        $('.option').removeClass('active');
        $('.option input').attr('checked', '');
        $(this).addClass('active');
        $(this).children('input').attr('checked', 'checked');
    });
    $('#upgradeOptions table div').click(function() {

        if ($('#upgradeForm').attr('class') == 'unregistered') {
            return false;
        }
        if ($('#upgradeOptions').attr('class') == 'about') {
            return false;
        }

        var upgradeLevel = $(this).parent().attr('class');

        $('#upgradeOptions table div').removeClass('active');
        $('.' + upgradeLevel + ' div').addClass('active');

        $("input[name=upgrades]").removeAttr("checked");

        var radioButton = $("#" + upgradeLevel + "Radio");


        var upgradeType = radioButton.attr('rel');
    //    pageTracker._trackEvent('Test', 'UpgradeClicked', upgradeType);

        radioButton.attr("checked", "checked");

        $("#addQuestion").hide(); //hide the feedback question unless we need it
        feedbackDirty = true;
        switch (parseInt(radioButton.val())) {
            case 0:
                $("#addInstruction").hide();
                $("#addQuestion").hide();
                $("#controlRandom .count:first-child").text('4');
                break;
            case 1:
                $("#addInstruction").hide();
                $("#addQuestion").hide();
                $("#controlRandom .count:first-child").text('4');
                break;
            case 2:
                $("#addInstruction").show();
                $("#addQuestion").hide();
                $("#addInstruction .count:first-child").text('4');
                $("#controlRandom .count:first-child").text('5');
                break;
            case 3:
                $("#addInstruction").show();
                $("#addQuestion").show();
                $("#addQuestion .count:first-child").text('5');
                $("#addInstruction .count:first-child").text('4');
                $("#controlRandom .count:first-child").text('6');
                feedbackDirty = false;
                break;
        }



    });

});


function SetSliderPosition(value) {
    $('#slider').slider('option', 'value', values[parseInt(value) + currentSpend]);
    SetSliderColour();
    UpdateTokenValue(value);
}

function SetSliderColour() {
    var width = $('.ui-slider-range').css('width').slice(0, -1);
    $('.ui-slider-range').css('background', GetSliderRGB(width));
}

function UpdateTokenValue(value) {
   // value = value - currentSpend;
    $(".actions .left #tokenValue").text(value);
    if (value > $("#tokensOwned").val()) {
        $("#currentTokens").css("color", "red");
    }
    else {
        $("#currentTokens").css("color", "");
    }
    if (value == 1) {
        $(".actions .left #tokenText").text("token");
    }
    else {
        $(".actions .left #tokenText").text("tokens");
    }
}
function findNearest(includeLeft, includeRight, value) {
    var nearest = null;
    var diff = null;
    var foundId = null;
    for (var i = 0; i < values.length; i++) {
        if ((includeLeft && values[i] <= value) || (includeRight && values[i] >= value)) {
            var newDiff = Math.abs(value - values[i]);
            if ((diff == null || newDiff < diff)&& (i>=currentSpend)) {
                nearest = values[i];
                diff = newDiff;
                foundId = i;
            }
        }
    }
    if (foundId > -1) {
        UpdateTokenValue(foundId - currentSpend);
    }
    return nearest;
}




function GetSliderRGB(width) {
    var pow2 = Math.pow(width, 2)
    var red = Math.round((-0.0161143 * pow2) + (1.03943 * width) + 226.257)
    var green = Math.round((-0.0174857 * pow2) + (2.48057 * width) + 129.543)
    var blue = Math.round((0.00594286 * pow2) - (0.610286 * width) + 109.229)

    return "#" + red.toString(16) + green.toString(16) + blue.toString(16) 
}
function clearAction(elem) {
    var parent = $(elem).parents('.testBox .actions');
    var child = $(elem);
    child.removeClass('active');
    parent.animate({ width: '53px' }, 200);
}

function openAction(elem) {
    var child = $(elem);
    var parent = child.parents('.actions');
    var siblings = child.parents('ul').children('li').children('a');
    if (child.hasClass('active')) {
        clearAction(elem);
        return false;
    }
    siblings.each(function() { $(this).removeClass('active'); });
    child.addClass('active');
    parent.animate({ width: '200px', border: '0' }, 200);
}

function resizePage(width) {

    $('.shim').remove();
    if (width > 1280) {
        $('.wrapper').removeClass('wSmall wMedium');
        $('.wrapper').addClass('wLarge');
        $('.floated .floatBox').removeClass('last').css('marginRight', '44px');
        $('.floated .floatBox:nth-child(5n)').addClass('last').css('marginRight', '0').after('<div class="shim"></div>');
    }
    else if (width > 1024) {
        $('.wrapper').removeClass('wSmall wLarge');
        $('.wrapper').addClass('wMedium');
        $('.floated .floatBox').removeClass('last').css('marginRight', '45px');
        $('.floated .floatBox:nth-child(4n)').addClass('last').css('marginRight', '0').after('<div class="shim"></div>');
    }
    else {
        $('.wrapper').removeClass('wLarge wMedium');
        $('.wrapper').addClass('wSmall');
        $('.floated .floatBox').removeClass('last').css('marginRight', '47px');
        $('.floated .floatBox:nth-child(3n)').addClass('last').css('marginRight', '0').after('<div class="shim"></div>');
    }
}

function deleteTest(url, elem) {
    var parentBox = $(elem).parents('.testBox')
    
    $(elem).parents('.testPrompt').html('<span class="loading">deleting</span>');
    
    $.post(url, null, function(data) {
       parentBox.fadeOut("slow", function() {
             $(this).remove();
              resizePage($(window).width());
        });
    });
}

function lockTest(url, elem) {
    var parentBox = $(elem).parents('.testBox');
  
   parentBox.find('.loading').show().html('locking');
    parentBox.find('.lockPrompt').hide();


    $.post(url, null, function(data) {
        // alert($(elem).parents('.testBox').html());        
        parentBox.find('.actionUnlock').show();
        parentBox.find('.actionLock').hide();
        parentBox.find('.actionMoreResults').hide()
        
        parentBox.find('.priorityBox').hide();
        parentBox.find('#private').show();
        
        parentBox.find('.loading').hide();
        clearAction(parentBox.find('.active'));
    });
}

function upgradeTest(url, elem) {

    var parentBox = $(elem).parents('.testBox');
  
   parentBox.find('.loading').show().html('upgrading');
    parentBox.find('.upgradePrompt').hide();


    $.ajax({ type: "POST",
        url: url,
        data: 'tokens=1',
        dataType: "json",
        success: function(data, textStatus) {

            if (data["success"]) {
                parentBox.find("#notpaid").hide();
                parentBox.addClass("premium");
                parentBox.find('.loading').hide();
                clearAction(parentBox.find('.active'));

            }
            else {
                alert("something went wrong, please try again later. " + data["message"]);
            }

        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("FAILED");
        }
    });
}


function moreResults(url, elem) {

    var parentBox = $(elem).parents('.testBox');

    parentBox.find('.loading').show().html('upgrading');
    parentBox.find('.moreResults').hide();


    $.ajax({ type: "POST",
        url: url,
        data: 'tokens=1',
        dataType: "json",
        success: function(data, textStatus) {

            if (data["success"]) {
                window.location = window.location;

            }
            else {
                alert("something went wrong, please try again later. " + data["message"]);
            }

        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("FAILED");
        }
    });
}

function unlockTest(url, elem) {
    var parentBox = $(elem).parents('.testBox');
 
    parentBox.find('.loading').show().html('unlocking');
    parentBox.find('.unlockPrompt').hide();

     $.post(url, null, function(data) {
         parentBox.find('.actionUnlock').hide();
         parentBox.find('.actionLock').show()
         parentBox.find('.actionMoreResults').show()
         
         parentBox.find('.priorityBox').show();
        parentBox.find('#private').hide();
         
         parentBox.find('.loading').hide();
         clearAction(parentBox.find('.active'));
     });
}


function appeal(url, elem) {
    var parentBox = $(elem).parents('.testBox')
    $(elem).parents('.appealPrompt').html('<span class="loading">pleading</span>');

    $.post(url, null, function(data) {
         parentBox.find('.appealPrompt').html('<p>Your appeal is pending.</p><a class="close" href="#">&rarr; close</a>');        
         clearAction(parentBox.find('.active'));
    });
}

//function Upgrade() {
//    var value = parseInt($(".actions .left #tokenValue").text());
//    var adminCode = $("#adminCode").val();
//    $('#priority').dialog('close');
//    $('#waiting').dialog({
//        modal: true,
//        height: 180,
//        width: 332
//    });

//    $('#waiting').dialog('open');
//    $.ajax({
//        type: "POST",
//        url: "/tokens/upgrade",
//        data: { adminCode: adminCode, tokens: value },
//        dataType: 'json',
//        success: function(data, textStatus) {
//            //do something awesome
//            $('#waiting').dialog('close');
//            if (data["success"]) {
//                window.location = window.location;
//            }
//            else {
//                alert("something went wrong, please try again later." + data["message"]);
//            }

//        },
//        error: function() {
//            $('#waiting').dialog('close');
//            alert("total fail");
//            //do something not so awesome
//        }

//    });
//    return false;
//}
//function priorityDialog(currentTokens, adminCode) {

//    currentSpend = currentTokens;
//    $('#priority').dialog({
//        modal: true,
//        height: 180,
//        width: 332
//    });

//    $('#priority').dialog('open');
//    
////    $(".tokenCount").each(function() {
////        $(this).text($(this).text()-currentSpend);
////        if($(this).text()<0){
////            $(this).hide();
////        }
////        else{
////           $(this).show();
////        }
////    });

//    $("#adminCode").val(adminCode);
//    SetSliderPosition(0);

//    $('#priority .cancel').click(function() {
//        $('#priority').dialog('close');
//        return false;
//    });
//    
//    return false;
//}

function newTest() {

    $('#upgradeOptions').dialog('close');
    
    $('#newTest').dialog({
        modal: true,autoOpen: false,
        height: 280,
        width: 528
    });

    $("#newTest").parent().appendTo($("form:first"));
    $('#newTest').dialog('open'); 
    
    $('#newTest .cancel').click(function() {
        $('#newTest').dialog('close');
        return false;
    });


    $('#newTest .back').click(function() {
        $('#newTest').dialog('close');
        $("#upgradeOptions").parent().appendTo($("form:first"));
        $('#upgradeOptions').dialog('open');
        return false;
    });
    
    return false;
}

function upgradePrompt() {
window.location="/test/new";
// 

//        $('#upgradeOptions').dialog({
//            modal: true,autoOpen: false,
//            width: 528
//        });

//        $("#upgradeOptions").parent().appendTo($("form:first"));
//        $('#upgradeOptions').dialog('open');

//        $('#upgradeOptions .cancel').click(function() {
//            $('#upgradeOptions').dialog('close');
//            return false;
//        });

        return false;
   
}

function submitUpgradeForm() {
   if ($("#imageCode").val() != "") {//check for upload
        $('.upgradeOptn').each(function() {
            if ($(this).attr('checked') == 'checked') {
                var upgradeType = $(this).attr('rel');
              //  pageTracker._trackEvent('Test', 'UpgradeSelected', upgradeType);
               // pageTracker._trackPageview('/test/new/upgrade/' + upgradeType);
            }
        });
       // pageTracker._trackPageview('/test/new/finish');
        $("#upgradeForm").submit()
    }
    else {
        alert("Please upload an image");
    }
}

function validateExtras() {
//debugger;
//    if (questionDirty && feedbackDirty) {
        submitUpgradeForm();
//    }
//    else {
//        alert("please complete all fields");        
//        return false;
//    }
}
function extrasPrompt() {

    $('#newTest').dialog('close');
    
    $('#upgradeExtras').dialog({
        modal: true,
        width: 528
    });

    $("#upgradeExtras").parent().appendTo($("form:first"));
    $('#upgradeExtras').dialog('open');

    $('#upgradeExtras .responseInput input').blur();
    $('#upgradeExtras .responseInput textarea').blur();

    $('#upgradeExtras .responseInput input').focus(function() {
        if ($(this).val() == 'e.g. please locate all the product titles') {
            $(this).val('');
            $(this).addClass('active');
        }
        else {
            $(this).select()
        }
    });
    $('#upgradeExtras .responseInput input').blur(function() {
        if ($(this).val() == '') {
            $(this).val('e.g. please locate all the product titles');
            $(this).removeClass('active');
            questionDirty = false;
        }
        else {
            questionDirty = true;
        }
    });
    $('#upgradeExtras .responseInput textarea').focus(function() {
        if ($(this).val() == 'e.g. was our logo too big or small?') {
            $(this).val('');
            $(this).addClass('active');
        }
        else {
            $(this).select()
        }
    });
    $('#upgradeExtras .responseInput textarea').blur(function() {
        if ($(this).val() == '') {
            $(this).val('e.g. was our logo too big or small?');
            $(this).removeClass('active');
            feedbackDirty = false;
        }
        else {
            feedbackDirty = true;
        }
    });

    $('#upgradeExtras .cancel').click(function() {
        $('#upgradeExtras').dialog('close');
        return false;
    });

    $('#upgradeExtras .back').click(function() {
        $('#upgradeExtras').dialog('close');
        $('#newTest').dialog('open');
        return false;
    });

    return false;
}

function upgradeDialog() {
    $('#priority').dialog({
        modal: true,
        height: 290,
        width: 528
    });
    $('#priority').dialog('open');

    
    $('#priority .cancel').click(function() {
        $('#priority').dialog('close');
        return false;
    });

    return false;
}

function upgradeTestFromDialog(url, elem) {

    $(elem).hide();


    $.ajax({ type: "POST",
        url: url,
        data: 'tokens=1',
        dataType: "json",
        success: function(data, textStatus) {

            if (data["success"]) {
                $('#priority').dialog('close');
                window.location.reload();
            }
            else {
                alert("something went wrong, please try again later. " + data["message"]);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("FAILED");
        }
    });
}


function appealInline(url) {
    $.post(url, null, function(data) {
        window.location.reload();
    });
}

