$(document).ready(function(){
    //initialise
    //- Hide all conference description boxes. Will need to make a switch function if we want to toggle between long and shors description...
    $(".conf_desc").hide();
    //- Hook up description expand handlers:
    $(".conf_time").click(function(){
        conf_desc_expand($(this).siblings(".conf_desc"));
        return false;
    });
    $(".more_info").click(function(){
        conf_desc_expand($(this).parent().siblings(".conf_desc"));
        return false;
    });
    $(".less_info").click(function(){
        conf_desc_expand($(this).parent());
        return false;
    });
    
    var defaultInitDisplay = true;
    //- Hide all conference panels exept for the first wich will be the default:
    $(".conf_day").each(function(){
        if (defaultInitDisplay == true){
            defaultInitDisplay = false;
            $(this).find(".conf_day_stand > .view_pane").each(function(){
                check_arrow_visibility($(this));
            });
            
        }else{
            $(this).hide();
        }
    });
    switch_day_tab(1);
    //- Hook up day tab anchors with function to switch between days:
    $(".day_tab li").click(function(){
        //-- Extract day number
        var strDayNumber = this.id.substring(9,this.id.length - 1);
        switch_conf_day(strDayNumber);
        switch_day_tab(strDayNumber);
        return false;
    });
    init_conf_scroll();

    //add another event handler for the click event of the #aConference link.
    //this fixes the disappearing content in ie 7 & 8:
    //$("#aConference").click(function(){});
});

var arrConf = new Array();
function add_conference(strConfID, strConfTitle, strConfDate, strConfTime,  strStandNumber){
        //alert(strConfID);
        //check that this conference item doesnt already exist in arrConf:
        var boolChkExists = false;
        for(var c=0;c<arrConf.length;c++){
            //arrConf contains: confID,title,date,time,standnumber,standreference
            if(arrConf[c][0] == strConfID){
                boolChkExists = true;
            }
        }
        if(!boolChkExists){
            //the empty string at index[5] will contain the stand reference number
            arrConf.push(new Array(strConfID, strConfTitle, strConfDate, strConfTime, strStandNumber, ''));
            window.document.showplan.SetVariable("javaAdd",strStandNumber)
        }
}

function removeConf(strConfID){
   /* REMOVE ONE CONFERENCE FROM arrConf GIVEN THE conferenceID
    * if this conf item is the last item to reference this
    * particular stand number then remove the stand from the
    * event plan too

    arrConf contains: confID,title,date,time,standnumber,standreference

    */
    //- get the stand number before removing the entry
    var arrNewConf = new Array();
    for (var i=0;i<arrConf.length;i++){
        if(arrConf[i][0] != strConfID){
            arrNewConf.push(arrConf[i]);
        }
    }
    arrConf = arrNewConf;

    reListStands();

}

function removeAllConf(){

    //arrConf contains: confID,title,date,time,standnumber,standreference

    //- get the stand number before removing the entry
    for(var c=0; c<arrConf.length;c++){
        var strStandNumber = arrConf[c][4];
        showplan_DoFSCommand("delStand", strStandNumber);
        getFlashMovieObject("showplan").SetVariable("javaDel",strStandNumber);
    }
    arrConf = new Array();
    reListStands();

}

function check_conf_assoc(strStandNo, strStandRefNo){
   /* CONFERENCE ARRAY OPERATIONS
    * Scan check to see if this stand is included in the conference array.
    * if it's found then we amend the conference array with the correct
    * stand reference number.

    //arrConf contains: confID,title,date,time,standnumber,standreference
    */
    for(var p=0;p<arrConf.length;p++){
            if(arrConf[p][4]==strStandNo){
                    arrConf[p][5] = strStandRefNo;
            }
    }

    /* END CONFERENCE ARRAY OPERATIONS */
}

function conf_remove_stand(strStandNo){
    //arrConf contains: confID,title,date,time,standnumber,standreference
    var arrNewConf = new Array();
    for(var c=0;c<arrConf.length;c++){
        if(arrConf[c][4] != strStandNo){
            arrNewConf.push(arrConf[c]);
        }
    }
    arrConf = arrNewConf;
}

function generate_conf_grid(){
    /* OUTPUT CONFERENCE GRID */
    var outhtm="";
    if(arrConf.length > 0){
        outhtm="<tr><td colspan='7'>Conference debates</td></tr>";

        outhtm+="<tr><th scope='col' class='userstandid'>&nbsp;</th><th scope='col' class='userstandexhibitor'>Date and time</th><th scope='col' class='userstandstand'>Stand</th><th scope='col' class='userstandsection' colspan='3'>Debate details</th><th scope='col' class='userstandremove'><input type='image' src='images/grid_removeall.jpg' value='Remove All' onclick='removeAllConf();return false;' /></th></tr>";
        for (var tmpConfRow in arrConf){
                //arrConf contains: confID,title,date,time,standnumber,standreference
                outhtm+="<tr>";
                outhtm+="<td class='userstandid'>"+checkForNull(arrConf[tmpConfRow][5],"error")+"</td>"; //stand reference code
                outhtm+="<td class='userstandexhibitor'>"+ checkForNull(arrConf[tmpConfRow][2],"") + " from " + checkForNull(arrConf[tmpConfRow][3],"")+"</td>"; //scheduled start time
                outhtm+="<td class='userstandstand'>"+checkForNull(arrConf[tmpConfRow][4],"")+"</td>"; //stand number
                outhtm+="<td class='userstandsection' colspan='3'>"+checkForNull(arrConf[tmpConfRow][1],"")+"</td>"; //debate details
                outhtm+="<td class='userstandremove'><input type='image' src='images/grid_remove.jpg' value='Remove' onclick='removeConf(\""+checkForNull(arrConf[tmpConfRow][0],"")+"\");return false;' /></td>";
                outhtm+="</tr>";

        }
    }
    return outhtm;

    /* END CONFERENCE OUTPUT GRID */
}

/*
 * Utilities specifically linked to conference functionality
 **/

function switch_conf_day(daynumber){
    //- Loop through each conference day <li> item:
    $(".conf_day").each(function(){
        //- Make sure we dont fade out the specified day panel
        if(this.id != ("divDayPanel" + daynumber)){
            //-- Check if this panel is currently open:
            if($(this).is(":visible")){
                //--- freeze the height of #divConferenceArea
                //if($.browser.msie){
                    var strHeightFreeze = $("#divConferenceArea").height();
                    $("#divConferenceArea").css("height", strHeightFreeze)
                //}
                //--- close it:
                $(this).fadeOut("slow",function(){
                    //once weve faded out the old open panel fade in the one specified:
                    $("#divDayPanel"+daynumber).fadeIn("slow",function(){
                        $(this).find(".conf_day_stand > .view_pane").each(function(){
                            var intNewLeftPos = get_left($(this).children(".canvas"));
                            check_arrow_visibility($(this), intNewLeftPos);
                            //unfreeze the height of #divConferenceArea
                            if($.browser.msie){
                                $("#divConferenceArea").css("height", $("#divDayPanel"+daynumber).outerHeight() + $(".day_tab:first").height() + 20);
                            }else{
                                $("#divConferenceArea").css("height", "auto");
                            }
                        })
                        
                    });
                    
                    
                });
            }
        }
       
    });

    
    
    //- Open the specified conference day <li>

}

function conf_desc_expand(divConfDesc){

    divConfDesc.each(function(){
        var divConfDesc = $(this);
        if(divConfDesc.is(":visible")){
            $(this).siblings(".conf_time:first").css("background-image", "url(images/conference/arrowdown.png)");
            $(this).siblings(".conf_desc_short").show();
            divConfDesc.slideUp("fast",function(){
                divConfDesc.parent().addClass("conf_item_closed");
                if($.browser.msie){
                    $("#divConferenceArea").css("height", $(".conf_day_panel").outerHeight() + $(".day_tab:first").height() + 20);

                }
            });
        } else {
            $(this).siblings(".conf_time:first").css("background-image", "url(images/conference/arrowup.png)");
            $(this).siblings(".conf_desc_short").hide();
            divConfDesc.parent().removeClass("conf_item_closed");
            divConfDesc.slideDown("fast",function(){
                if($.browser.msie){
                    $("#divConferenceArea").css("height", $(".conf_day_panel").outerHeight() + $(".day_tab:first").height() + 20);
                }
            });
        }
    });
}

function switch_day_tab(daynumber){
    /*$(".day_tab li").each(function(){
        if(this.id != ("liDayTab" + daynumber)){
            $(this).css("background-color", "#373737");
        }else{
            $(this).css("background-color", "#707070");
        }
    });*/

    //highlight the selected day tab
    $(".day_tab > li").css("background-position", "0px 0px");
    $("#liDayTab" + daynumber).css("background-position", "0px -30px");

    $(".day_tab > li > a").css("color", "#434343");
    $("#liDayTab" + daynumber + " > a").css("color", "#FFFFFF");
}

/****************** Functions dealing with conference scrolling *******************/
function init_conf_scroll(){
    $(".conf_day_stand").each(function(){
        $(this).children(".arrow_left").click(conf_scroll);
        $(this).children(".arrow_right").click(conf_scroll);
        $(this).children(".arrow_left").hide();
        
    });
}

function resize_canvases(dayPanel){
    $(dayPanel).children(".conf_day_stand").each(function(){
        var divLastConfItem = $(this).children(".view_pane > .canvas > .conf_item:last");
        var intCanvasWidth = divLastConfItem.offset().left + divLastConfItem.width();
        $(this).children(".view_pane > .canvas").each(function(){
            $(this).css("width", intCanvasWidth + "px");
        });
        
    });
}

function conf_scroll(e){
    //intJumpAmount is the distance travelled when an arrow is clicked
    var intJumpAmount = 150;
    //alert("trying to scroll!");
    var intNewLeftPos = 0;
    var divViewPane = $(e.target).siblings(".view_pane");
    var divCanvas = divViewPane.children(".canvas");
    
    switch($(e.target).attr("class")){
        case "arrow_left":
            //calculate the new left position
            var intCurrentLeftPos = get_left(divCanvas);
            intNewLeftPos = intCurrentLeftPos += intJumpAmount;
            
            break;
        case "arrow_right":
            //calculate the new left position
            var intCurrentLeftPos = get_left(divCanvas);
            intNewLeftPos = intCurrentLeftPos -= intJumpAmount;
            //-run checks on new left position:
            //calculate the leftmost position:
            var divLastConfItem = divCanvas.children(".conf_item:last")
            //var intCanvasWidth = divLastConfItem.offset().left + divLastConfItem.width();
            var intCanvasWidth = calculate_canvas_width(divCanvas);
            
            
    }
    
    //this (set of) if statements check that we dont scroll beyond our 
    //boundaries and shows/hides the left and right arrows:
    if((-intNewLeftPos + divViewPane.width()) > intCanvasWidth){
        //too far left
        intNewLeftPos = divViewPane.width() - intCanvasWidth;
    }else if(intNewLeftPos > 0){
        //too far right
        intNewLeftPos = 0;
    }
    
    $(e.target).siblings(".view_pane").children(".canvas").animate({left:intNewLeftPos}, 200,function(){
        //check_arrow_visibility($(e.target).parent(".conf_day_stand"));
        check_arrow_visibility(divViewPane);
    })

    
    
    return false;
}

function check_arrow_visibility(divViewPane){
    var intCanvasWidth = calculate_canvas_width($(divViewPane).children(".canvas:first"))
    var intNewLeftPos = get_left($(divViewPane).children(".canvas:first"));
    if(intCanvasWidth > $(divViewPane).width()){
        //the canvas is larger than the view pane so do check for the following conditions:
        //- the canvas still has some distance to travel left but not right
        //- the canvas still has some distance to travel right but not left
        //- the canvas still has some distance to travel both right and left
        if((-intNewLeftPos + divViewPane.width()) >= intCanvasWidth){
            $(divViewPane).siblings(".arrow_right").hide();
            $(divViewPane).siblings(".arrow_left").show();
        }else if(intNewLeftPos == 0){
            $(divViewPane).siblings(".arrow_right").show();
            $(divViewPane).siblings(".arrow_left").hide();
        }else{
            $(divViewPane).siblings(".arrow_right").show();
            $(divViewPane).siblings(".arrow_left").show();
        }
        
    }else{
        //the canvas is smaller than the viewpane so hide both arrows:
        $(divViewPane).siblings(".arrow_left").hide();
        $(divViewPane).siblings(".arrow_right").hide();
    }
    
}

/*function check_arrow_visibility(confDayStand){
    var divViewPane = $(confDayStand).children(".view_pane");
    var divCanvas = divViewPane.children(".canvas");
    var divLastConfItem = divCanvas.children(".conf_item:last");
    //var intCanvasWidth = divLastConfItem.offset().left + divLastConfItem.width();
    var intCanvasWidth = calculate_canvas_width(divCanvas);

    if(divViewPane.width() < intCanvasWidth){
        if(divCanvas.offset().left < (divViewPane.width() - intCanvasWidth)){
            $(confDayStand).children(".arrow_right").hide();
        }else if(divCanvas.offset().left >= 0){
            $(confDayStand).children(".arrow_left").hide();
        }
    } else {
        $(confDayStand).children(".arrow_right").hide();
        $(confDayStand).children(".arrow_left").hide();
    }
}*/

function calculate_canvas_width(divCanvas){
        var runningWidthCount = 0;
        $(divCanvas).children(".conf_item").each(function(){
            runningWidthCount += $(this).outerWidth(true);
        });
        return runningWidthCount;
}

function get_left(element){
    var returnVal = 0;
    if($(element).css("left") != "auto"){
        returnVal = parseInt($(element).css("left"));
    }
    return returnVal;
}

function fix_ie_height(daynumber){
    if($.browser.msie){
        $("#divConferenceArea").css("height", $("#divDayPanel"+daynumber).outerHeight() + $(".day_tab:first").height() + 20)
    }
}