﻿var body;
var wrapper;
var imgSource;
var screenshot;
var formTag;
var welcome;
var startTest;
var numberOfNotes = 5;
var annotations;
var testType;
var testArea;
var tag;
var handle;
var tagCount = 0;
var imgLoader;
var firstClick;
var imageHeight;
var windowHeight;
var imageWidth;
var currentTest;
var prompt;
var skipInstructions;
var imgHolder;
var showCustomQuestion;
var customQuestion;


function newTest(type) {
    skipInstructions = false;   
    

    //initialise variables
    var aType;
    var aWelcome = '<br />';
    var aStartButton;
    var aStep1 = $('<div class="instruction">you have 5 seconds</div>');
    var aStep2;
    var aStep3;
    aStartButton = '<button onclick="javascript:start_test();">start test</button><br /><a class="cancel" href="/">go back home</a>';
   
    //set up type switching
    switch (type) {
        case 0:
        
//            if ($.cookie("MemoryTest") == "true") {
//                skipInstructions = true;
//            }           
            aType = 'memory';
            $.cookie("MemoryTest", "true")
            var aStep0 = $('<div class="instruction">this is a memory test</div>');
            var aStep2 = $('<div class="instruction">just look at the following image</div>');
            var aStep3 = $('<div class="instruction">list things you remember</div>');
            
            break;
        case 1:
//            if ($.cookie("ClickTest") == "true") {
//                skipInstructions = true;
//            }
            aType = 'click';
            $.cookie("ClickTest", "true")
            var aStep0 = $('<div class="instruction">this is a click test</div>');
            var aStep2 = $('<div class="instruction">click on areas that stand out</div>');            
            var aStep3 = $('<div class="instruction">describe what you clicked on</div>');
            break;
        default:
            return false;
    }
    
    //override with custom question
    if (showCustomQuestion) {
        aCustomStep = $('<div class="instruction">' + customQuestion + '</div>');
    }
    else {
     aCustomStep=""
    }
    
    //repeat test overrides
    if (welcome) aWelcome = welcome;
    if (startTest) aStartButton = startTest;

    //return values
    return {
        type: aType,
        welcome: aWelcome,
        //instruction: aInstruction,
        start: aStartButton,
        step0: aStep0,
        step1: aStep1,
        step2: aStep2,
        step3: aStep3,
        customStep:aCustomStep
    }

}


$(function() {

    //initialise a new test
    currentTest = newTest(testType);


    body = $('body');
    wrapper = $('#test_content');
    imgLoader = $('<div id="img_loader"></div>');
    imgHolder = $('<div id="image_holder"> </div>');

    loadVars();


    //add spinner
    var spinner = $('<div class="spinner"><img src="/images/spinner.gif" alt="spinner" /></div>');

    imgHolder.append(spinner);
    wrapper.append(imgLoader.append(imgHolder));

    screenshot.load(function() {
    resizeWindow(); 
    
        if (imageHeight < 300) {
            imgHolder.css('height', 300);
        }
        else {
            imgHolder.css('height', imageHeight);
        }
        spinner.html(currentTest.welcome);
        spinner.append(currentTest.start);

    });

});
function skip() {
    $("form").submit();

}
function loadVars() {

    //load screenshot into dom
    screenshot = $('<img>').attr('src', imgSource);

    if (currentTest.type == 'click') {

        
        
        //load tag into dom
        tag = $('<div class="test_tag" style="display:none">' +
                    '<label>what is this</label>' +
                    '<a href="#">remove</a>' +
                    '<input type="text"> </input>' +
                    '<input type="hidden" id="x" />' +
                    '<input type="hidden" id="y" />' +
                '</div>');
        handle = $('<div class="handle">' + '</div>');
    }

}

function start_test() {

    var clickImg = $('<img src="/images/click.png" />');

    imgHolder.empty();
    imgLoader.css('zIndex', '1001');



    imgLoader.queue(function() {
        $(this).append($("<a href='/test/random' class='skip' id='tip_skip' onclick='skip()'  rel='skip this test'><span>skip this test</span></a><a href='/test/" + viewcode + "/report' class='report' id='tip_report'  rel='report this test'><span>report this image</span></a><br />"));
        $(this).append(formTag);
        imgHolder.append(screenshot.css('display', 'none'));


        $(this).dequeue();
        JT_init()

    });


    testArea = $('<div id="test_area"> </div>');
    formTag.append(testArea);
    testArea.css("display", "none");
    testArea.css("width", imageWidth);
    testArea.css("height", imageHeight);

   
    testArea.queue(function() {
        $.scrollTo(imgLoader, 500);
        $(this).dequeue();
    })
        .animate({ opacity: 1.0 }, 500)
        .queue(function() {
            formTag.append(currentTest.step0.fadeIn(500));
            $(this).dequeue();
        })
        .animate({ opacity: 1.0 }, 1500)
        .queue(function() {
            $(".instruction").fadeOut(500);
            $(this).dequeue();
        })
        .animate({ opacity: 1.0 }, 500)
        
    if( !skipInstructions )
    { 
        testArea.queue(function() {
                formTag.append(currentTest.step1.fadeIn(500));
                $(this).dequeue();
            })
            .animate({ opacity: 1.0 }, 1500)
            .queue(function() {
                $(".instruction").fadeOut(500);
                $(this).dequeue();
            })
            .animate({ opacity: 1.0 }, 500)
            .queue(function() {
                formTag.append(currentTest.step2.fadeIn(500));
                $(this).dequeue();
            })
            .animate({ opacity: 1.0 }, 1500)
            .queue(function() {
                $(".instruction").fadeOut(500);
                $(this).dequeue();
            })
            .animate({ opacity: 1.0 }, 500)
        }

        if (showCustomQuestion && customQuestion != '') {
        testArea.queue(function() {
                formTag.append(currentTest.customStep.fadeIn(500));
                $(this).dequeue();
            })
            .animate({ opacity: 1.0 }, 4500)
            .queue(function() {
                $(".instruction").fadeOut(500);
                $(this).dequeue();
            })
            .animate({ opacity: 1.0 }, 500)
        }
    
    testArea.queue(function() {
            $('img').fadeIn(500);
            $(this).fadeIn(500);
            $(this).dequeue();
        });

    setupTest();

    haveClicked = false;
    testOver = false;

    imgLoader.append(prompt);
    testArea.queue(function() {
        var timer = setTimeout("end_test()", 5000);
        $(this).dequeue();
    });


    fadeOut();

}

function setupTest() {

    if (currentTest.type == 'click') {
        testArea.click(function(e) {
            createTestTag(e, $(this));
            if (testOver) {
                prompt.remove();
            }
            haveClicked = true;
        });
    }
    else if (currentTest.type == 'memory') {
        testArea.css('cursor', 'default');
    }

}


function createTestTag(e, theTestArea) {
    if (tagCount < 5) {
        tagCount++;

        var aTag = tag.clone();
        var aHandle = handle.clone();
        aTag.attr('id', 'clone' + tagCount);
        aHandle.attr('id', 'clone' + tagCount);
        aTag.css({ 'top': e.pageY - theTestArea.offset().top, 'left': e.pageX - theTestArea.offset().left });
        aHandle.css({ 'top': e.pageY - theTestArea.offset().top - 10, 'left': e.pageX - theTestArea.offset().left - 10 });
        aTag.children("input[type=text]").attr("id", "keyword" + tagCount).attr("name", "keyword" + tagCount).attr("tabindex", tagCount).focus();
        aTag.children("input[type=text]").keypress(function(e) {
            if (e.which == 13) {
                aTag.next().next().children('[type=text]').focus();
                return false;
            }
        });
        aTag.children("#x").attr("id", "x" + tagCount).attr("name", "x" + tagCount).val(e.pageX - theTestArea.offset().left - 10);
        aTag.children("#y").attr("id", "y" + tagCount).attr("name", "y" + tagCount).val(e.pageY - theTestArea.offset().top - 10);

        testArea.append(aTag);
        testArea.append(aHandle);

        setTagBehaviours();
    }
}

function setTagBehaviours() {

    var tagHandles = $('.handle');
    var tagInputs = $(".test_tag");

    tagHandles.draggable({
        handle: tagHandles,
        containment: testArea,
        drag: function(e, ui) {
            $(this).prev().css('top', (ui.position.top - 1) + "px").css('left', (ui.position.left - 1) + "px");
        }
    }).mouseover(function() {
        tagHandles.css("zIndex", "1");
        tagInputs.css("zIndex", "1");
        $(this).css("zIndex", "100").prev().css("zIndex", "99");

    }).prev().mouseover(function() {
        tagHandles.css("zIndex", "1");
        tagInputs.css("zIndex", "1");
        $(this).css("zIndex", "99").next().css("zIndex", "100");

    });

    tagInputs.children("a").click(function() {
        $(this).parent().next().remove();
        $(this).parent().remove();

        tagCount--;
        return false;
    });

    $("textarea").click(function() {
        $(this).select();
    });

    $('.test_tag').click(function() {
        return false;
    });

    $('.handle').click(function() {
        return false;
    });

}

function end_test() {

    testOver = true;       
        

        switch (currentTest.type) {
            case 'memory':
                if (!skipInstructions) {

                    testArea.queue(function() {
                        $('#image_holder').fadeOut(500);
                        $(this).dequeue();
                    })
                        .animate({ opacity: 1.0 }, 500)
                        .queue(function() {
                            formTag.append(currentTest.step3.fadeIn(500));
                            $(this).dequeue();
                        })
                        .animate({ opacity: 1.0 }, 1500)
                        .queue(function() {
                            $(".instruction").fadeOut(500);
                            $(this).dequeue();
                        })
                        .animate({ opacity: 1.0 }, 500)
                        .queue(function() {
                            $('#img_loader').animate({ height: 350, width: 300 }, 500);
                            $(this).dequeue();
                        })
                        .animate({ opacity: 1.0 }, 500)
                        .queue(function() {
                            $('#test_area').css({ 'height': '350px', 'width': '300px' });
                            $(this).dequeue();
                        })
                        .animate({ opacity: 1.0 }, 500)
                        .queue(function() {
                            var i = 1;
                            var responseInput = $('<div class="response_input"><input type="text" tabindex="2"> </input></div>');
                            while (i < numberOfNotes + 1) {
                                var aResponse = responseInput.clone();
                                aResponse.children("input[type=text]").attr('id', 'keyword' + i);
                                aResponse.children("input[type=text]").attr('name', 'keyword' + i);
                                testArea.append(aResponse).fadeIn(200);
                                $('input#keyword' + i).keypress(function(e) {
                                    if (e.which == 13) {
                                        $(this).parent().next().children('input[type=text]').focus();
                                        return false;
                                    }
                                });
                                i++;
                            }
                            $('input#keyword1').focus();
                            $(this).dequeue();
                        });
                }
                else {
                    testArea.queue(function() {
                        $('#image_holder').fadeOut(500);
                        $(this).dequeue();
                    })
                        .animate({ opacity: 1.0 }, 500)
                        .queue(function() {
                            $('#img_loader').animate({ height: 350, width: 300 }, 500);
                            $(this).dequeue();
                        })
                        .animate({ opacity: 1.0 }, 500)
                        .queue(function() {
                            $('#test_area').css({ 'height': '350px', 'width': '300px' });
                            $(this).dequeue();
                        })
                        .animate({ opacity: 1.0 }, 500)
                        .queue(function() {
                            var i = 1;
                            var responseInput = $('<div class="response_input"><input type="text" tabindex="2"> </input></div>');
                            while (i < numberOfNotes + 1) {
                                var aResponse = responseInput.clone();
                                aResponse.children("input[type=text]").attr('id', 'keyword' + i);
                                aResponse.children("input[type=text]").attr('name', 'keyword' + i);
                                testArea.append(aResponse).fadeIn(200);
                                $('input#keyword' + i).keypress(function(e) {
                                    if (e.which == 13) {
                                        $(this).parent().next().children('input[type=text]').focus();
                                        return false;
                                    }
                                });
                                i++;
                            }
                            $('input#keyword1').focus();
                            $(this).dequeue();
                        });
                }
                break;

            case 'click':
                if (!skipInstructions) {
                    testArea.queue(function() {
                        $('#image_holder').fadeTo(500, 0.5);
                        $(this).dequeue();
                    })
                        .animate({ opacity: 1.0 }, 500)
                        .queue(function() {
                            formTag.append(currentTest.step3.css('zIndex', '999').fadeIn(500));
                            $(this).dequeue();
                        })
                        .animate({ opacity: 1.0 }, 1500)
                        .queue(function() {
                            $(".instruction").fadeOut(500);
                            $(this).dequeue();
                        })
                        .animate({ opacity: 1.0 }, 500)
                        .queue(function() {
                            $('.test_tag').show(); //display the tag inputs
                            $('.handle').draggable('disable'); //disable tag dragging
                            testArea.unbind("click"); //no more clicking!
                            $(this).dequeue();
                        });
                }
                else {
                    testArea.queue(function() {
                        $('#image_holder').fadeTo(500, 0.5);
                        $(this).dequeue();
                    })
                        .animate({ opacity: 1.0 }, 500)
                        .queue(function() {
                            $('.test_tag').show(); //display the tag inputs
                            $('.handle').draggable('disable'); //disable tag dragging
                            testArea.unbind("click"); //no more clicking!
                            $(this).dequeue();
                        });
                }
                break;

            default:
                return false;

        }

        //add the submit button
        formTag.append("<button class='confirmTest' type='submit' value='done'><span>submit</span></button>");
        $(this).dequeue();

}

function fadeOut() {
    var fader = $('<div id="fader"> </div>');
    body.append(fader);

    fader.width($(document).width());
    fader.height($(document).height());
    fader.css('background', '#222');
    fader.css('opacity', '0.9');
    fader.fadeIn("fast");
    $(window).resize(function() {
        fader.width($(this).width());
        fader.height($(this).height());
        fader.width($(document).width());
        fader.height($(document).height());

    });
}

function resizeWindow() {

    //add the image to dom to get size
    body.append(screenshot.css('display', 'none'));

    //initialise dimension variables
    imageHeight = screenshot.height();
    windowHeight = $(window).height();
    imageWidth = screenshot.width();
    windowWidth = $(window).width();
    //resizing
    if (imageHeight > windowHeight- 74) {
        imageHeight = windowHeight - 74;
    }
     if (imageWidth > windowWidth- 86) {
        imageWidth = windowWidth - 86;
    }
    else if (imageHeight < 300) {
        imageHeight = 300;
    }
    if (imageWidth < 500) { imageWidth = 500; }

    //remove image after resizing
    screenshot.remove();

    //animate the imgLoader
    imgLoader.animate({ height: imageHeight, width: imageWidth }, 500, "linear", function() {
        imgLoader.prepend(currentTest.instruction);
    });

}
