var dreamTotal = 4;
var dreamItems = 0;

if ( ! jQuery) {
    var $ = jQuery.noConflict();
} else {
    var $ = jQuery;
}

$(document).ready(function() {

    resetForm();

    $(".targetButton").click(function() {

        var idButton = this.value;

        // default page
        if (idButton == 'Self ' + dreamit_stage)
        {
            location = dreamit_pageLocation;
        }
        else if (idButton == 'Person ' + dreamit_stage)
        {
            location = dreamit_pageLocation + 'target/person';
        }
        else if (idButton == 'Place ' + dreamit_stage)
        {
            location = dreamit_pageLocation + 'target/place';
        }
        else if (idButton == 'Event ' + dreamit_stage)
        {
            location = dreamit_pageLocation + 'target/event';
        }
        else if (idButton == 'Object ' + dreamit_stage)
        {
            location = dreamit_pageLocation + 'target/object';
        }
    });    

    $(".reportSelectorButton").click(function() {

        var idButton = this.value;

        if (idButton == 'Circle')
        {
            $("#reportTableCircle").show();
            $("#reportTableWords").hide();
            $("#reportDisplayWords").hide();
        }
        else if (idButton == 'Words')
        {
            $("#reportTableCircle").hide();
            $("#reportTableWords").show();
            $("#reportDisplayWords").show();

            if (document.getElementById("reportItemTitle").innerHTML == '')
            {
                document.getElementById("reportItemTitle").innerHTML = reports['Create']['title'];
                document.getElementById("reportItemTagline").innerHTML = reports['Create']['tagline'];
                document.getElementById("reportItemReport").innerHTML = reports['Create']['report'];
                document.getElementById("reportItemQuestions").innerHTML = reports['Create']['questions'];
            }
        }
        else if (idButton == 'PDF')
        {
            return;
        }
        else if (idButton == 'Send to my e-mail')
        {
            return;
        }       
    });
    
    $(".reportButton").click(function() {

        var idButton = this.value;

        document.getElementById("reportItemTitle").innerHTML = reports[idButton]['title'];
        document.getElementById("reportItemTagline").innerHTML = reports[idButton]['tagline'];
        document.getElementById("reportItemReport").innerHTML = reports[idButton]['report'];
        document.getElementById("reportItemQuestions").innerHTML = reports[idButton]['questions'];

        $("#reportTableCircle").hide();
        $("#reportTableWords").show();
        $("#reportDisplayWords").show();
    });
    
    $("#clickKeywords").click(function() {

        if (document.getElementById("word").value == "")
        {
            $("#message1").show();
            $("#message1 td").text("Please enter a word...").show();
            setTimeout('$("#message1").hide();', 2000);
            return false;
        }

        if (jQuery("#" + dreamit_target).val() == "person") {
          if (jQuery("input[@name='gender']:checked").val() === undefined) {
            $("#message1").show();
            $("#message1 td").text("Please enter the gender...").show();
            setTimeout('$("#message1").hide();', 2000);
            return false;
        }
        }

        if (document.getElementById("dream_description").value == "")
        {
            $("#message1").show();
            $("#message1 td").text("Please enter a short description...").show();
            setTimeout('$("#message1").hide();', 2000);
            return false;
        }        

        $("#showKeywords").animate({
            opacity: "show"
        });

        $("html, body").animate({
            scrollTop: $("#showKeywords").offset().top
        }, 1000);
    });

    if (document.getElementById("showKeywordsList2"))
    {
        jQuery("#showKeywordsList2").tableDnD({
            onDragClass: "myDragClass"
        });
    }

    $("#myForm").submit(function() {

        if (dreamItems < dreamTotal) {
          
            $('html, body').animate({
                scrollTop: $("#showKeywords").offset().top
            }, 1000);
                      
            $("#message2").show();
            $("#message2 td").text("Please choose the most important 12 keywords...").show();
            setTimeout('$("#message2").hide();', 3000);
            return false;
        }

        var orderKeywords = new Array();
        var mytable = document.getElementById("showKeywordsList2");
        
        for (i = 1; i <= dreamTotal; i++)
        {
            var myrow = mytable.getElementsByTagName("tr")[i];
            var mycel = myrow.getElementsByTagName("td")[0];
            var data = mycel.innerHTML;

            orderKeywords[i - 1] = data;
        }

        document.getElementById("orderKeywords").value = orderKeywords.join("|");

        return true;
    });

    /** ------------------- */

    $("#inputLocation1Click").click(function() {
        if (document.getElementById("inputLocation1Data").value == "") {
            $("#inputLocation1Report").show();
            $("#inputLocation1Report td").text("Please input code to embed...").show();
            setTimeout('$("#inputLocation1Report").hide();', 2000);
            return false;
        }

        switch (inputType) {
            case "text" :
            $("#inputLocation1DataCell").html("");
            resetTable();
            var aux = $("#inputLocation1Data").val();
            processWords(aux);
            break;
            case "image" :
            // resize
            case "sound" :
            case "video" :
            $("#inputLocationShow").show();
            $("#inputLocationShowData").html($("#inputLocation1Data").val());
            break;
        }
    });

    $("#inputLocation2Click").click(function() {
        if (document.getElementById("inputLocation2Data").value == "") {
            $("#inputLocation2Report").show();
            $("#inputLocation2Report td").text("Please input link...").show();
            setTimeout('$("#inputLocation2Report").hide();', 2000);
            return false;
        }

        // validate link

        switch (inputType) {
            case "image" :
            case "sound" :
            case "video" :
            var aux = document.getElementById("inputLocation2Data").value;
            // improve to accept more protocols
            aux = aux.replace(/^http:\/\/|https:\/\//g, "");
            $("#inputLocationShow").show();
            $("#inputLocationShowData").html('<a target="_blank" href="http://' + aux + '">' + aux + '</a>');
            break;
        }
    });
    
    $("#inputLocation3Click").click(function() {
        $("#myForm").ajaxSubmit({
            url:        dreamit_pageLocation + "ajax/1",
            dataType:   null,
            success:    processUpload
        });        
    });
    
    $("#inputLocationKeywordsClick").click(function() {
        if ($("#inputLocationKeywords").val() == "") {
            $("#inputLocationKeywordsReport").show();
            $("#inputLocationKeywordsReport td").text("Please fill the field...").show();
            setTimeout('$("#inputLocationKeywordsReport").hide();', 2000);
            return false;
        }

        resetTable();

        var str = $("#inputLocationKeywords").val();

        str = str.replace(/[^a-zA-Z\s]/g, "");
        str = str.replace(/\s{2,}/g, " ");
        var strArray = str.split(" ");
        var obj = new Object();

        $(strArray).each(function (i) {
            obj.value = strArray[i];
            setKeyword(obj, "text");    
        });        
    });    
    
});

function resetTable()
{
    var mytable = document.getElementById("showKeywordsList2");
    
    for (i = 1; i <= dreamTotal; i++)
    {
        var myrow = mytable.getElementsByTagName("tr")[i];
        var mycel = myrow.getElementsByTagName("td")[0];
        var data = mycel.innerHTML;

        mycel.innerHTML = "&nbsp;";
    }    
}

function resetForm()
{
    if ( ! document.getElementById("myForm"))
        return;
    
    var frm_elements = document.getElementById("myForm").elements;
    
    for(i = 0; i < frm_elements.length; i++)
    {
        field_type = frm_elements[i].type.toLowerCase();

        switch(field_type)
        {
            case "text":
            frm_elements[i].value = "";
            break;

            case "checkbox":
            if (frm_elements[i].checked)
            {
                frm_elements[i].checked = false;
            }
            if (frm_elements[i].disabled)
            {
                frm_elements[i].disabled = false;
            }            
            break;
        }
    }
}

function setKeyword(input, type) {
    var text = input.value;
    
    var mytable = document.getElementById("showKeywordsList2");

    if (type != "text")
    if (type == "span") {
        if (dreamItems == dreamTotal && input.className.indexOf("spanOn") >= 0) {
            input.className = "span spanOff";
            setSpan(1);            
        } else
            setSpan(0);
    } else {
        if (dreamItems == dreamTotal && input.checked == true) {
            input.checked = false;
            setcheckBox(1);            
        } else
            setcheckBox(0);
    }

    for (i = 1; i <= dreamTotal; i++) {
        var myrow = mytable.getElementsByTagName("tr")[i];
        var mycel = myrow.getElementsByTagName("td")[0];
        var data = mycel.innerHTML

        if (data == text) {
            mycel.innerHTML = "&nbsp;";

            dreamItems--;

            /** allow drag after select all keywords
             ** or fail when uncheck after drag */
            $("#showKeywordsList").animate({
                opacity: "hide"
            });
            
            if (dreamItems != dreamTotal)
                return;
        }
    }

    if (i != dreamTotal)
    for (i = 1; i <= dreamTotal; i++) {
        var myrow = mytable.getElementsByTagName("tr")[i];
        var mycel = myrow.getElementsByTagName("td")[0];
        var data = mycel.innerHTML
   
        if (data == "&nbsp;") {
            mycel.innerHTML = text;

            dreamItems++;

            if (dreamItems != dreamTotal)
                return;
        }
    }

    if (type != "text")
    if (type == "span")
        setSpan(1);
    else
        setcheckBox(1);

    $("#showKeywordsList").animate({
        opacity: "show"
    });

/*    $('html, body').animate({
        scrollTop: $("#showKeywordsList").offset().top
    }, 1000);
    *
    */
}

var inputType = "";
function setInput(input, method) {
    inputType = input.value
    document.getElementById("inputMethod").value = method;

    resetTable();

    $("#inputLocation1Data").show();
    $("#inputLocation1DataCell").html("");
    $("#inputLocation1").hide();
    $("#inputLocation2").hide();
    $("#inputLocation3").hide();

    $("#inputLocation" + method).show();

    /*$("#inputLocation" + method).animate({
        opacity: "show"
    });*/

    $("input:file").eq(0).val("");
    $("#inputLocation" + method + "Data").focus();
    $("#inputLocation" + method + "Data").val("");

    //$("#inputLocationShow").hide();



    
    //$("#inputLocationShowData").html("&nbsp;");

    var instructionstext = "Text:";
    var instructionssound = "Sound (mp3 format):";
    var instructionsimage = "Image (png, jpg, jpeg, gif, bmp, wbmp):";
    if (method == 3)
        var instructionsvideo = "Video (flv format): ";
    else
        var instructionsvideo = "Video: ";

    var instructions = eval("instructions" + inputType);

    $("#inputLocation" + method + "Instructions").text(instructions).show();

    /*$('html, body').animate({
        scrollTop: $("#inputLocation" + method).offset().top
    }, 1000);    */
}

function processUpload(jsonWords, statusText) {
    var aux = jsonWords.split("|");
    var myfile = dreamit_urlLocation + 'wp-content/upload/' + aux[1]
    
    $("#inputLocationShow").show();
    $("#inputLocationShowData").html("");
    
    if (aux[0] == 'image')
        $("#inputLocationShowData").html('<img src="' + myfile + '" />');
    else if (aux[0] == 'flv') {
        var so = new SWFObject(dreamit_urlLocation + 'wp-content/plugins/dreamit-core/php/mediaplayer/player.swf', 'mpl', '320', '240', '7');
        so.addParam("allowfullscreen", "true");
        so.addVariable("file", myfile);
        so.addVariable("displayheight", "240");
		so.addVariable("logo", dreamit_urlLocation + 'wp-content/plugins/dreamit-core/php/mediaplayer/watermark.png');
		so.addVariable("showstop", "true");
		so.addVariable("autostart", "true");
		so.addVariable("allowfullscreen", "true");
        //so. addParam('flashvars','file='+mov+'&autostart=true');
        so.write('inputLocationShowData');
    }
    else if (aux[0] == 'mp3' || aux[0] == 'wav') {

        var newLink = '<a class="media" href="' + myfile + '">'+myfile+'</a>';
        $('#inputLocationShowData').append(newLink);
        //$('.media').media();
        $('.media').media( { width: 300, height: 20 } );
    }    
    else
        $("#inputLocationShowData").html('player available soon!');
}

function processWords(str) {
    var word;
	var newspan;
	var cellText;
	var data;

    str = str.replace(/[^a-zA-Z\s]/g, "");
    str = str.replace(/\s{2,}/g, " ");
    $("#inputLocation1Data").hide();
    $("#inputLocation1DataCell").show();
    var strArray = str.split(" ");

    var output1 = document.getElementById("inputLocation1DataCell");

    for (i = 0; i < strArray.length; i++) {
        word = strArray[i];
        newspan = document.createElement("span");
        newspan.id = "span" + i;
        newspan.className = "span spanOff";        
        newspan.innerHTML = word;
        newspan.value = word;
        output1.appendChild(newspan);
        cellText = document.createTextNode(" ");
        output1.appendChild(cellText);
        newspan.onclick = function() { setClick(this) };
    }
}

function setClick(obj) {
    if (obj.className.indexOf("spanOn") >= 0)
        obj.className = "span spanOff";
    else
        obj.className = "span spanOn";
    setKeyword(obj, "span");
};

function setcheckBox(disable) {
    var elements = document.getElementById("myForm").elements;
    
    for(i = 0; i < elements.length; i++) {
        if (elements[i].type.toLowerCase() == "checkbox") {
            if (disable) {
                if (elements[i].checked == false) {
                    elements[i].disabled = true;
                }
            } else {
                elements[i].disabled = false;
            }
        }
    }
}

function setSpan(disable) {
    var elements = document.getElementById("inputLocation1DataCell").getElementsByTagName("span");
    
    for(i = 0; i < elements.length; i++) {
        if (disable) {
            if (elements[i].className.indexOf("spanOff") >= 0) {
                elements[i].onclick = function() {};
                elements[i].className = "span spanNull";
            }
        } else {
            elements[i].onclick = function() { setClick(this) };
            if (elements[i].className.indexOf("spanNull") >= 0) {
                elements[i].className = "span spanOff";
            }
        }
    }
}