﻿/// <reference path="jquery-1.3.2.js" />
var scrollmaxy = 0;
var scrollmaxx = 0;

var curstage = 0;

var colwidth = 160;
var mycolwidth = 198;
var tbarspacing = 35;
var collastmin = [0, 0];

var mycols = [[], []];

var seluser = 0;
var othercoll = [];

var dlistuniverse;
var mdlistuniverse;
var odlistuniverse;
var headerdiv;


var fullscreenmode = false;
var isInIFrame = (window.location != window.parent.location) ? true : false;

document.onselectstart = new Function('return false');

$(document).ready(function () {
    $("#StagePlannerTab").show();

    hideotherbar();
    //$('#helpdiv').hide();

    dlistuniverse = $('#' + dlistuniversecid);
    mdlistuniverse = $('#' + mdlistuniversecid);
    odlistuniverse = $('#' + odlistuniversecid);
    headerdiv = $('#' + headerdivcid);


    scrollmaxy = -(Number($('#dayslistsub').height())) + Number($('#dayslistcontainer').height());
    scrollmaxx = -(Number($('#dayslistsub').width())) + Number($('#dayslistcontainer').width());

    if (scrollmaxx > 0) {
        scrollmaxx = 0;
    }
    if (scrollmaxy > 0) {
        scrollmaxy = 0;
    }

    var dragDeltadays = {
        top: $('#dayslistcontainer').position().top +
             dlistuniverse.position().top,
        left: $('#dayslistcontainer').position().left +
              dlistuniverse.position().left
    };

    var viewportdays = $('#dayslistcontainer');
    $('#dayslistscrolloverlay')
          .css('left', viewportdays.css('left'))
          .css('top', viewportdays.css('top'))
          .css('width', viewportdays.width())
          .css('height', viewportdays.height())
          .css('z-index', 95)
          .css('display', '');


    $('#dayslistscrolloverlay').draggable({
        helper: function () {
            return $("<div />");
        },
        start: function (ev, ui) {
            var offset = dlistuniverse.position();
            dlistuniverse
              .data("top0", offset.top)
              .data("left0", offset.left);
            //alert($('#universe').data("top0") + "/" + $('#universe').data("left0"));
        },
        drag: function (ev, ui) {
            var offset = dlistuniverse.position();

            var dragTop = ui.position.top + dlistuniverse.data("top0") - dragDeltadays.top;
            var dragLeft = ui.position.left + dlistuniverse.data("left0") - dragDeltadays.left;

            setpos(dragLeft, dragTop, false);

        },
        stop: function (ev, ui) {
            var toppos = ui.position.top + dlistuniverse.data("top0") - dragDeltadays.top;
            var leftpos = ui.position.left + dlistuniverse.data("left0") - dragDeltadays.left;
            if (toppos > 0) {
                toppos = 0;
            }
            if (leftpos > 0) {
                leftpos = 0;
            }
            if (toppos < scrollmaxy) {
                toppos = scrollmaxy;
            }
            if (leftpos < scrollmaxx) {
                leftpos = scrollmaxx;
            }
            curstage = -Math.floor(leftpos / colwidth);
        },
        refreshPositions: false
    });

    var dragDeltamyday = {
        top: $('#mydaylistcontainer').position().top +
             mdlistuniverse.position().top,
        left: $('#mydaylistcontainer').position().left +
              mdlistuniverse.position().left
    };

    var viewportmydays = $('#mydaylistcontainer');
    $('#mydaylistscrolloverlay')
          .css('left', viewportmydays.css('left'))
          .css('top', viewportmydays.css('top'))
          .css('width', viewportmydays.width())
          .css('height', viewportmydays.height())
          .css('z-index', 99)
          .css('display', '');

    $('#mydaylistscrolloverlay').draggable({
        helper: function () {
            return $("<div />");
        },
        start: function (ev, ui) {
            var offset = mdlistuniverse.position();
            mdlistuniverse
              .data("top0", offset.top)
              .data("left0", offset.left);
            //alert($('#universe').data("top0") + "/" + $('#universe').data("left0"));
        },
        drag: function (ev, ui) {
            var offset = mdlistuniverse.position();

            var dragTop = ui.position.top + mdlistuniverse.data("top0") - dragDeltamyday.top;
            var dragLeft = ui.position.left + mdlistuniverse.data("left0") - dragDeltamyday.left;

            setpos(dragLeft, dragTop, false);
        },
        refreshPositions: false
    });

    // OTHER SCHEDULE DAYS DRAG
    var dragDeltaotday = {
        top: $('#otherdaylistcontainer').position().top +
             odlistuniverse.position().top,
        left: $('#otherdaylistcontainer').position().left +
              odlistuniverse.position().left
    };

    var viewportotdays = $('#otherdaylistcontainer');
    $('#otherdaylistscrolloverlay')
          .css('left', viewportotdays.css('left'))
          .css('top', viewportotdays.css('top'))
          .css('width', viewportotdays.width())
          .css('height', viewportotdays.height())
          .css('z-index', 99)
          .css('display', '');

    $('#otherdaylistcontainer').draggable({
        helper: function () {
            return $("<div />");
        },
        start: function (ev, ui) {
            var offset = odlistuniverse.position();
            odlistuniverse
              .data("top0", offset.top)
              .data("left0", offset.left);
            //alert($('#universe').data("top0") + "/" + $('#universe').data("left0"));
        },
        drag: function (ev, ui) {
            var offset = odlistuniverse.position();

            var dragTop = ui.position.top + odlistuniverse.data("top0") - dragDeltaotday.top;
            var dragLeft = ui.position.left + odlistuniverse.data("left0") - dragDeltaotday.left;

            setpos(dragLeft, dragTop, false);
        },
        refreshPositions: false
    });


    ///CLICK HANDLERS FOR BOXES
    var startx;
    var starty;

    //NOT USED ANYMORE
    /*$('#dayslistscrolloverlay')
    .mousedown(
    function(e, ui) {
    var offset = $(e.target).offset(false);
    startx = e.pageX - offset.left;
    starty = e.pageY - offset.top;
    //alert("CLICKED " + e.clientX + "/" + e.pageX + "/" + offset.left + "/" + startx);
    })
    .mouseup(
    function(e) {
    var offset = $(e.target).offset(false);
    var x = e.pageX - offset.left;
    var y = e.pageY - offset.top;

    var diffx = startx - x;
    var diffy = starty - y;

    if (diffx < 5 && diffx > -5 && diffy < 5 && diffy > -5) {
    var posx = x - (dlistuniverse.position().left);
    var posy = y - (dlistuniverse.position().top);
    var clickedstage = Math.floor(posx / colwidth);
    var clickedstageid = stages[clickedstage];

    for (r = 0; r < daysentries.length; r++) {
    if (daysentries[r].StageID == clickedstageid) {
    if (posy > daysentries[r].StartMinute && posy < (daysentries[r].StartMinute + daysentries[r].TotalMinutes)) {
    alert(daysentries[r].BandName);
    }
    }
    }
    //alert('CLICK : ' + clickedstageid + '/' + clickedstage + ' X : ' + posx + ' Y : ' + posy);
    //alert("MOUSE UP " + clickedstageid + "/" + x + "/" + dlistuniverse.position().left + "/" + posx + " y :" + y + "/" + starty + "/" + diffy);
    }
    });*/



    //add filter link func
    $('.filterlink').hover(
					function () {
					    var fstr = $(this).attr("rel").toLowerCase().replace(' ', '');
					    $('.bblock').each(function () {
					        if (!$(this).hasClass(fstr)) {
					            $(this).removeClass('highlight');
					        } else {
					            //alert($(this).text());
					            $(this).addClass('highlight');
					        }
					    });
					},
					function () {
					    $('.bblock').each(function () {
					        $(this).removeClass('highlight');
					    });
					}
				);

    //CHANGE OF A-Z Select Box
    $("select#bandsselect").change(
                function () {
                    if ($(this).val() != "") {
                        scrolliteminview($(this).val());
                    }
                }
		);

    ///CONTROLLERS
    $('#navleft').bind(
            'click',
            function () {
                var selstage = (curstage - 1);
                if (selstage >= 0) {
                    setpos(-(selstage * colwidth), dlistuniverse.position().top, true);
                }
            }
        );

    $('#navright').bind(
            'click',
            function () {
                var selstage = (curstage + 1);
                setpos(-(selstage * colwidth), dlistuniverse.position().top, true);
            }
        );

    $('#navup').bind(
            'click',
            function () {
                setpos(dlistuniverse.position().left, dlistuniverse.position().top + 30, false);
            }
        );

    $('#navdown').bind(
            'click',
            function () {
                setpos(dlistuniverse.position().left, dlistuniverse.position().top - 30, false);
            }
        );




    $(".navel").hover(
        function () {
            $(this).children("img").attr("src", $(this).children("img").attr("src").replace(/\.png$/, 'h.png'));
        },
        function () {
            $(this).children("img").attr("src", $(this).children("img").attr("src").replace(/\h.png$/, '.png'));
        }
    );


    $(document).keydown(function (e) {
        var keyCode = e.keyCode || e.which,
                  arrow = { left: 37, up: 38, right: 39, down: 40 };
        switch (keyCode) {
            case arrow.up:
                setpos(dlistuniverse.position().left, dlistuniverse.position().top + 30, false);
                //$(document).scrollTop(110);
                return false;
                break;
            case arrow.down:
                setpos(dlistuniverse.position().left, dlistuniverse.position().top - 30, false);
                //$(document).scrollTop(110);
                return false;
                break;
            case arrow.left:
                var selstage = (curstage - 1);
                if (selstage >= 0) {
                    setpos(-(selstage * colwidth), dlistuniverse.position().top, true);
                }
                return false
                break;
            case arrow.right:
                var selstage = (curstage + 1);
                setpos(-(selstage * colwidth), dlistuniverse.position().top, true);
                return false
                break;
        }
    });


    ///MOUSE WHEEL SUPPORT
    var intOverallDelta = 0;

    function domousewheel(objEvent, intDelta) {
        if (intDelta > 0) {
            intOverallDelta++;
            setpos(dlistuniverse.position().left, dlistuniverse.position().top + 10, false);
            //$("#testdiv").html('up - (' + intOverallDelta + ')');
        }
        else if (intDelta < 0) {
            intOverallDelta--;
            setpos(dlistuniverse.position().left, dlistuniverse.position().top - 10, false);
            //$("#testdiv").html('down - (' + intOverallDelta + ')');
            //dlistuniverse.css('top',"+=" + (intDelta * 10));
        }

        objEvent.stopPropagation();
        objEvent.preventDefault();
    }

    $("#dayslistscrolloverlay").mousewheel(domousewheel);
    $("#mydaylistscrolloverlay").mousewheel(domousewheel);
    $("#otherdaylistscrolloverlay").mousewheel(domousewheel);

    loadday(null, initday[0], initday[1], initday[2]);


    if (cuser.userid > 0) {
        $('#publishfb').bind(
            'click',
            function () {

                $.jmsajax({
                    url: "/plingg_api/WS/StagePlanner.svc/GetCompleteStageString",
                    data: { EventID: eventid },
                    success: function (data) {
                        var attachment = {
                            'name': 'I finished planning the ' + festivalname + ' festival with the plingg Stage Planner',
                            'href': document.location.href,
                            'caption': '{*actor*} finished planning the ' + festivalname + ' festival with the plingg Stage Planner. Take a look online to see my stage plan and plan your own.',
                            'description': data,
                            'media': [{ 'type': 'image', 'src': 'http://' + festivallogourl, 'href': document.location.href}]
                        };

                        var actionLinks = [{ "text": "Create your own stage plan for the '" + festivalname + "' festival", "href": document.location.href },
                       { "text": "Find other festivals on plingg", "href": "http://www.plingg.com"}];

                        FB.Connect.streamPublish('I am really looking forward to this festival. Create your own stage plan so that we can share it.', attachment, actionLinks);


                    }
                });
            });
    } else {
        $('#publishfb').hide();
    }

    $("#StagePlannerTab").css("display", "");


    $('a#fullscreenlink').bind('click', function () {
        if (isInIFrame == false) {
            if (fullscreenmode == false) {
                $("#CommonBody div.Common").width("99%");
                fullscreenmode = true;
            } else {
                $("#CommonBody div.Common").width("998px");
                fullscreenmode = false;
            }
        } else {
            window.open("lineup.aspx");
        }
        return false;
    });

});

function setpos(leftpos, toppos, animated) {
    if (toppos > 0) {
        toppos = 0;
    }
    if (leftpos > 0) {
        leftpos = 0;
    }

    //alert(toppos + " /" + scrollmaxy);
    
    if (toppos < scrollmaxy) {
        toppos = scrollmaxy;
    }
    if (leftpos < scrollmaxx) {
        leftpos = scrollmaxx;
    }

    animated = false;
    if (animated == false) {
        dlistuniverse.css({ top: toppos, left: leftpos });

        headerdiv.css({ left: leftpos });

        mdlistuniverse.css({ top: toppos });

        if (odlistuniverse.is(":visible") == "true") {
            odlistuniverse.css({ top: toppos });
        }
        
    } else {
        $(dlistuniverse).animate({ top: toppos + 'px', left: leftpos + 'px' });
        $(headerdiv).animate({ left: leftpos + 'px' });
        $(mdlistuniverse).animate({ top: toppos + 'px' });
        $(odlistuniverse).animate({ top: toppos + 'px' });
    }

    
}

function loadday(sellink, dayi, monthi, yeari) {
    $("#loadingborder").show();
    $("#overallborder").hide();

    if (sellink != null && sellink != undefined) {
        $(".rectabs a").removeClass('active');
        $(sellink).addClass('active');
    }

    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: "/plingg_api/WS/StagePlanner.svc/GetEventStageBandsForUser?EventID=" + eventid + "&Day=" + dayi + "&Month=" + monthi + "&Year=" + yeari, // + JSON.stringify(dateIn),
        data: "",
        cache: false,
        dataType: "json",
        success: function (msg) {
            if (msg.d.length > 0) {
                //REMOVE ALL EXISTING
                $('.bblock').remove();

                ///RENDER LOADED ENTRIES
                daysentries = msg.d;


                ///SELECT OWN ENTRIES
                myentries = [];

                for (var i = 0; i < daysentries.length; i++) {
                    if (daysentries[i].IsBooked == true) {
                        myentries.push(daysentries[i]);
                    }
                }
                myentries.sort(function (a, b) {
                    return (a.StartMinute < b.StartMinute) ? -1 : 1;
                });

                addentries(daysentries, false);
                addentries(myentries, true);

                ///Render other schedule if selected
                if (seluser > 0) {
                    showuserschedule(null, seluser);
                }

                var fentryid = 0;

                daysentries.sort(function (a, b) {
                    if (a.StageID < b.StageID) {
                        return -1;
                    } else if (a.StageID == b.StageID) {
                        return (a.StartMinute < b.StartMinute) ? -1 : 1;
                    } else {
                        return 1;
                    }
                    
                });

                if (daysentries.length > 0) {
                    fentryid = daysentries[0].EventStageEntryID;
                }

                ///add bands to select box
                daysentries.sort(function (a, b) {
                    return (a.BandName < b.BandName) ? -1 : 1;
                });

                var options = '<option value="">Bands A-Z</option>'; ;
                for (var i = 0; i < daysentries.length; i++) {
                    if (daysentries[i].EntryType == 1) {
                        options += '<option value="' + daysentries[i].EventStageEntryID + '">' + daysentries[i].BandName + '</option>';
                    }
                }
                $("select#bandsselect").html(options);

                $("#loadingborder").hide();
                $("#overallborder").show();

                if (daysentries.length > 0) {
                    scrolliteminview(fentryid);
                }


            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("ERR : " + textStatus + "/" + errorThrown);
            this;
        }
    });
}


function addentries(ecoll, ismycoll, isothercoll) {
    var previtem;
    if (ismycoll == true) {
        mycols = new Array(2);
        mycols[0] = new Array();
        mycols[1] = new Array();
    }

    for (i = 0; i < ecoll.length; i++) {
        var specending = "my";

        var sb = new StringBuilder("");
        var sitem;
        if (ismycoll == false || (ismycoll == true && isothercoll == true)) {
            sitem = getitem(myentries, ecoll[i].EventStageEntryID);
        } else {
            sitem = ecoll[i];
        }

        if (ecoll[i].EntryType == 1) {
            sb.append('<div class="bblock ' + ecoll[i].GenreString.toLowerCase().replace('/', '') + ' ');
        } else {
            sb.append('<div class="bblock oblock ');
        }
        if (ecoll[i].FriendSelected != undefined) {
            if (ecoll[i].FriendSelected.length > 0) {
                for (u = 0; u < ecoll[i].FriendSelected.length; u++) {
                    sb.append("fr" + ecoll[i].FriendSelected[u]);
                    if (u < (ecoll[i].FriendSelected.length - 1)) {
                        sb.append(' ');
                    }
                }
            }
        }
        if (sitem != null && sitem != undefined) {
            sb.append(' selblock');
        }
        
        
        sb.append('" ');
        if (ismycoll == false) {
            sb.append('id="entryid' + ecoll[i].EventStageEntryID + '"');
        } else {
            if (isothercoll == true) {
                specending = "ot";
            }
            sb.append('id="entryid' + ecoll[i].EventStageEntryID + '_' + specending + '"');
            $('#entryid' + ecoll[i].EventStageEntryID + '_' + specending + '').remove();
        }
        var lstr = "";
        if ($.browser.msie) {
            lstr = "left:1px;";
        }

        sb.append(' rel="' + ecoll[i].EventStageEntryID + '" style="top:' + (ecoll[i].StartMinute * 2) + 'px;' + lstr + 'height:' + ((ecoll[i].TotalMinutes - 1) * 2) + 'px;">');
        if (ecoll[i].EntryType == 1) {
            //BAND ELEMENT
            //bstr += '<div class="blankimg"><img src="../images/blank.gif" width="250" height="' + (ecoll[i].TotalMinutes - 1) + '" onclick="alert(\'TEST\');" /></div>';

            

            sb.append('<div class="titleb">');
            //bstr += '<div class="i"><img src="' + ecoll[i].ImgURL + '"/></div>';
            sb.append('<div>');
            sb.append('<div class="t">' + ecoll[i].BandName + '</div>');
            sb.append('<div class="s">' + ecoll[i].TimeString + '</div>');
            sb.append('</div>');
            sb.append('</div>');
            sb.append('<div>');

            if (ismycoll == true) {
                sb.append('<span>');
                sb.append(stagenames[jQuery.inArray(ecoll[i].StageID, stages)] + '');
                if (ecoll[i].GenreString != '') {
                    sb.append(' - ' + ecoll[i].GenreString + '');
                }
                sb.append('</span>');
            } else {
                sb.append('<span>' + ecoll[i].GenreString + '</span>');
            }


            if (ecoll[i].FriendSelected != undefined) {
                if (ecoll[i].FriendSelected.length > 0) {
                    sb.append('<div class="frbox">');

                    var maxfriendstr = '';
                    var maxfriendcount = 0;

                    for (u = 0; u < ecoll[i].FriendSelected.length; u++) {
                        var fr = getfriend(ecoll[i].FriendSelected[u]);
                        if (fr != null) {
                            if (u < 5) {
                                if (String(fr.IM).indexOf('anonymous') > -1) {
                                    sb.append('<img src="' + fr.IM + '" title="' + fr.Name + '" width="20" height="20">');
                                } else {
                                    sb.append('<img src="' + fr.IM + '" title="' + fr.Name + '" width="20" height="20">');
                                }
                                if (u < (ecoll[i].FriendSelected.length - 1)) {
                                    sb.append(' ');
                                }
                            } else {
                                maxfriendstr += fr.Name;
                                maxfriendcount++;
                                if (u < (ecoll[i].FriendSelected.length - 1)) {
                                    maxfriendstr += ',';
                                }
                            }
                        }
                    }
                    if (maxfriendstr != '') {
                        //render others as + sign
                        sb.append(' &nbsp;<a href="javascript:{};" title="' + maxfriendcount + ' more friends (' + maxfriendstr + ')">+' + maxfriendcount + '</a>');
                    }


                    sb.append('</div>');
                }
            }



            if (sitem != null && sitem != undefined) {
                sb.append('<img src="/images/icons/rem.png" class="addlink" title="add / remove to your own schedule" />');
            } else {
                sb.append('<img src="/images/icons/add.png" class="addlink" title="add / remove to your own schedule" />');
            }
            if (ecoll[i].BandID > 0) {
                sb.append('<img src="/images/icons/info.png" class="infolink" title="view more info about this band" />');
            }
            sb.append('</div></div>');
        } else {
            //OTHER ELEMENT               
            sb.append('<div><b>' + ecoll[i].TimeString + ' ' + ecoll[i].BandName + '</b><br/>');
            sb.append('</div></div>');
        }


        if (ismycoll == false) {
            $(sb.toString())
               .appendTo($('#stage' + ecoll[i].StageID))

            /*$('#entryid' + ecoll[i].EventStageEntryID + '').click(function() {
                alert("DIRECT CLICK" + Number($(this).attr("rel")));
                showitem(Number($(this).attr("rel")));
            });*/
            
            var eblock = $('div#entryid' + ecoll[i].EventStageEntryID);

            $('img.addlink', eblock).click(function (event) {
                if (cuser.userid > 0 || isInIFrame == false) {
                    addlinkclick(this);
                } else {
                    $('#InfoWin div.jqmdMSG').html('<div style=\'text-align:center:font-size:22px;width:100%;padding:10px;\'><h2>Erstelle deinen eigenen Stageplan für das Frequency</h2><br/><div>Auf plingg.com kannst du dir deinen eigenen Stageplan erstellen, ihn ausdrucken, mit deinen Freunden teilen, auf Facebook veröffentlichen, jederzeit am Handy mobil abrufen und vieles mehr.</div><br/><a href=\'Lineup.aspx\' target=\'_blank\' style=\'font-size:20px;\'>Stageplan auf plingg.com erstellen >>></a></div>');
                    $('#InfoWin').jqm({
                        target: $('#InfoWin div.jqmdMSG'),
                        ajax: "",
                        overlayClass: 'jqmOverlay',
                        onShow: function (h) {
                            /* callback executed when a trigger click. Show notice */
                            h.w.css('opacity', 1).slideDown();
                            $('#InfoWin div.jqmdMSG').html('<div style=\'text-align:center:font-size:22px;width:100%;\'><br><br><br><img src=\'/images/loading.gif\' class=\'flag\'>' + ajtext + '<br><br><br></div>');
                        },
                        onHide: function (h) {
                            /* callback executed on window hide. Hide notice, overlay. */
                            h.w.slideUp("slow", function () { if (h.o) h.o.remove(); });
                        }
                    });
                    $("#InfoWin").jqmShow();
                }
                event.stopPropagation();
            });

            $('img.infolink', eblock).click(function (event) {
                showitem(this);
                event.stopPropagation();
            });

            eblock.qtip({
                content: {
                    url: "/plingg_api/AJAX/BandTT.aspx?BID=" + ecoll[i].BandID
                },
                position: {
                    corner: {
                        target: 'topMiddle',
                        tooltip: 'bottomMiddle'
                    },
                    adjust: {
                        x: 4
                    }
                },
                show: {
                    delay: 200,
                    effect: 'slide'
                },
                hide: {
                    fixed: true // Make it fixed so it can be hovered over
                },
                style: {
                    name: 'infostyle'
                }
            });
            
            
        } else {
            if (isothercoll == undefined || isothercoll == false) {
                $(sb.toString())
                   .appendTo($('#stage0'))
            } else {
                $(sb.toString())
                   .appendTo($('#stage-1'))
            }
            var selcol = 0;
            
            var entryblock = $('div#entryid' + ecoll[i].EventStageEntryID + '_' + specending + '')

            //CHECK FOR SPECIAL POSITIONING IN OWN COLUMN
            if (previtem != null) {
                //alert("CHECK : " + checkcolltime(mycols[0], ecoll[i]));

                if (checkcolltime(mycols[0], ecoll[i]) == true) {
                    //POS IN COLUMN 1
                    if (previtem.SelC == 1 && ecoll[i].StartMinute >= previtem.StartMinute && ecoll[i].StartMinute <= (previtem.StartMinute + previtem.TotalMinutes - 1)) {
                        entryblock.css('width', mycolwidth / 2 + 'px');
                    }

                    ecoll[i].SelC = 0;
                    mycols[0].push(ecoll[i]);
                } else {
                    //POS IN COLUMN 2
                    entryblock.css('width', mycolwidth / 2 + 'px');
                    entryblock.css('left', 4 + tbarspacing + (mycolwidth / 2) + 'px');
                    $('#entryid' + previtem.EventStageEntryID + '_' + specending + '').css('width', mycolwidth / 2 + 'px');
                    ecoll[i].SelC = 1;
                    mycols[1].push(ecoll[i]);
                }


            } else {
                //FIRST ITEM IN FIRST COLUMN
                mycols[0].push(ecoll[i]);
            }

            //add filter link func for own items so they are highlighted or scrolled to
            entryblock
                .hover(
                    function() {
                        $('#entryid' + $(this).attr('rel')).addClass('highlight');
                    },
                    function() {
                        $('#entryid' + $(this).attr('rel')).removeClass('highlight');
                    }
                )
                .click(function() {
                    scrolliteminview($(this).attr('rel'));
                });

                $('img.addlink', entryblock).click(function (event) {
                addlinkclick(this);
                event.stopPropagation();
            });

            $('img.infolink', entryblock).click(function (event) {
                showitem(this);
                event.stopPropagation();
            });

        }

        previtem = ecoll[i];
    }



    //
}

//CHECKS IF TIME IS IN COLUMN, RETURNS TRUE IF TIME AVAILABLE
function checkcolltime(col, sitem) {
    var retval = true;
    var sm = sitem.StartMinute;
    var em = sitem.StartMinute + sitem.TotalMinutes - 1

    for (u = 0; u < col.length; u++) {
        if (sm >= col[u].StartMinute && sm <= (col[u].StartMinute + col[u].TotalMinutes - 1)) {
            retval = false;
        }
        if (em >= col[u].StartMinute && em <= (col[u].StartMinute + col[u].TotalMinutes - 1)) {
            retval = false;
        }
    }
    return retval;
}


function addlinkclick(elem, dontdelete) {

    if (cuser.userid > 0) {

        //$(this).parents(".bblock").animate({ opacity: "hide" }, "slow");
        var sitem = getitem(daysentries, Number($(elem).parents(".bblock").attr("rel")));

        //alert("CLICKED ADD LINK " + sitem.BandName);
        var sindex;
        if (getitem(myentries, sitem.EventStageEntryID, sindex) == null) {
            /// not in my entries so remove it
            myentries.push(sitem);
            myentries.sort(function(a, b) {
                return (a.StartMinute < b.StartMinute) ? -1 : 1;
            });



            addentries(myentries, true);
            $('#entryid' + sitem.EventStageEntryID + ' .addlink').attr("src", $(elem).attr("src").replace(/\add.png$/, 'rem.png'));
            $('#entryid' + sitem.EventStageEntryID + '_ot .addlink').attr("src", $(elem).attr("src").replace(/\add.png$/, 'rem.png'));

            $('#entryid' + sitem.EventStageEntryID).addClass("selblock");

            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: "/plingg_api/WS/StagePlanner.svc/AddEventStageBandBookingForUser?EventStageEntryID=" + sitem.EventStageEntryID,
                data: "",
                cache: false,
                dataType: "json",
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    // typically only one of textStatus or errorThrown 
                    // will have info
                    alert("ERR : " + textStatus + "/" + errorThrown);
                    this; // the options for this ajax request
                }
            });


            $.jGrowl('Added <b>' + sitem.BandName + '</b> to your schedule !');
        } else {
            if (dontdelete != true) {
                /// remove from my entries
                $('#entryid' + sitem.EventStageEntryID + ' .addlink').attr("src", $('#entryid' + sitem.EventStageEntryID + ' .addlink').attr("src").replace('rem.png', 'add.png'));
                $('#entryid' + sitem.EventStageEntryID + '_ot .addlink').attr("src", $('#entryid' + sitem.EventStageEntryID + ' .addlink').attr("src").replace('rem.png', 'add.png'));
                $('#entryid' + sitem.EventStageEntryID + '_my').remove();

                $('#entryid' + sitem.EventStageEntryID).removeClass("selblock");

                $('#entryid' + sitem.EventStageEntryID).removeClass('highlight');

                myentries.splice(jQuery.inArray(sitem, myentries), 1);
                // Re render
                addentries(myentries, true);

                $.ajax({
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    url: "/plingg_api/WS/StagePlanner.svc/DeleteEventStageBandBookingForUser?EventStageEntryID=" + sitem.EventStageEntryID,
                    data: "",
                    cache: false,
                    dataType: "json",
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        // typically only one of textStatus or errorThrown 
                        // will have info
                        alert("ERR : " + textStatus + "/" + errorThrown);
                        this; // the options for this ajax request
                    }
                });

                $.jGrowl('Removed <b>' + sitem.BandName + '</b> from your schedule !');
            }
        }
    } else {
        showregistermodal();
    }
}

function showitem(elem) {
    var sitem = getitem(daysentries, Number($(elem).parents(".bblock").attr("rel")));
    showbandmodal(sitem.BandID);
}


function scrolliteminview(iid) {
    if ($('#entryid' + iid).length > 0) {
        var sitem = getitem(daysentries, iid);
        //X SCROLLING

        //$('#dayslistcontainer')

        var postop = -$('#entryid' + iid).position().top;
        var posleft = -(jQuery.inArray(sitem.StageID, stages) * 250);

        setpos(posleft, postop, true);
    }
}

function showuserschedule(el, iid) {

    $("#stage-1 .bblock").remove();

    var selfr = getfriend(iid);
    if (selfr != null) {
        //alert("USER ID : " + iid + "/" + selfr.Name + "/" + $("#otherstagelabel").length);

        var htstr = '';
        if (String(selfr.IM).indexOf('anonymous') > -1) {
            htstr += '<img src="' + selfr.IM + '" title="' + selfr.Name + '" width="20" height="20">';
        } else {
            htstr += '<img src="' + selfr.IM + '" title="' + selfr.Name + '">';
        }
        htstr += ' ' + selfr.Name + '\'s schedule';
        $("#otherstagelabel").html(htstr);

        othercoll = [];
        for (i = 0; i < daysentries.length; i++) {
            if (daysentries[i].FriendSelected != undefined) {
                if (daysentries[i].FriendSelected.length > 0) {
                    for (u = 0; u < daysentries[i].FriendSelected.length; u++) {
                        if (daysentries[i].FriendSelected[u] == iid) {
                            othercoll.push(daysentries[i]);
                        }
                    }
                }
            }
        }

        addentries(othercoll, true, true);
        showotherbar();
        seluser = iid;
    }
}

function copyotherschedule() {
    for (w = 0; w < othercoll.length; w++) {
        addlinkclick($('#entryid' + othercoll[w].EventStageEntryID + ' .addlink'), true);
    }
    $.jGrowl('Copied the schedule !');
}

function showotherbar() {
    $(".mainwin").css('margin-left', '457px');
    $(".leftbar").css('width', '455px');
    $(".innerobar").show();
}

function hideotherbar() {
    $(".mainwin").css('margin-left', '247px');
    $(".leftbar").css('width', '245px');
    $(".innerobar").hide();
    seluser = 0;
    $("#stage-1 .bblock").remove();
}

function getitem(coll, iid) {
    for (y = 0; y < coll.length; y++) {
        if (coll[y].EventStageEntryID == iid) {
            indid = y;
            return coll[y];
        }
    }
}

function getfriend(iid) {
    for (x = 0; x < friends.length; x++) {
        if (friends[x].ID == iid) {
            return friends[x];
        }
    }
}

function showhelp() {
    $('#helpdiv').slideToggle('normal');
}



if (!Array.prototype.forEach) {
    Array.prototype.forEach = function (fun /*, thisp*/) {
        var len = this.length >>> 0;
        if (typeof fun != "function")
            throw new TypeError();

        var thisp = arguments[1];
        for (var i = 0; i < len; i++) {
            if (i in this)
                fun.call(thisp, this[i], i, this);
        }
    };
}


var toArray = (function (slice) {
    return function toArray(object) {
        return slice.call(object, 0);
    }
})(Array.prototype.slice);

var StringBuilder = function (str) {
    var _stack = str ? [str] : [], // str == initial string to start, if any
        _length = str.length; // length of initial string

    this.separator = ''; // separator used when concatenating strings in the stack

    // public methods 

    this.append = function () {
        // append can take one or more strings as arguments
        _stack.push.apply(_stack, arguments);
        toArray(arguments).forEach(function (str) { _length += str.length });
        return this;
    }

    this.getLength = function () {
        return _length;
    }

    this.setLength = function (len) {
        // coalesce what we've already got and cut it to length
        // Note: this does not expand the string. it only clips it.
        _stack = [_coalesce(this.separator).substr(0, len)];
        _length = len;
        return this;
    }

    this.toString = function (altSeparator) {
        return _coalesce(altSeparator == undefined ? this.separator : altSeparator);
    }

    // private methods

    function _coalesce(separator) {
        // consolidates all of the string entries into one string
        var str = _stack.join(separator || '');
        _stack = [str];
        _length = str.length;
        return str;
    }
}

