YAHOO.namespace("artCloud.calendar");
YAHOO.util.Event.addListener(window, "load", calInit);

var whichCal = "world";
var calMonth = '';
var calYear = '';
var isin = false;
var calHighlightDates = null;

if (document.all && !document.getElementById) { document.getElementById = function(id) { return document.all[id]; } }

// check to see if we have a calendar control and then init the cal
function calInit()
{
    if (getElement("cal1Container"))
    {
	    YAHOO.artCloud.calendar.cal1 = new YAHOO.widget.Calendar("cal1", "cal1Container", { LOCALE_WEEKDAYS:"1char" } );
	    YAHOO.artCloud.calendar.cal1.cfg.setProperty("WEEKDAYS_1CHAR", ["s", "m", "t", "w", "t", "f", "s"]);

	    YAHOO.artCloud.calendar.cal1.selectEvent.subscribe(handleCalDateSelect, YAHOO.artCloud.calendar.cal1, true);
    	YAHOO.artCloud.calendar.cal1.changePageEvent.subscribe(getDatesOnClientChange, YAHOO.artCloud.calendar.cal1, true);

        getInitDates();
    }
}

// functions for highlighting dates with events behind them
function getInitDates() { _getAjaxDates(); }

function getDatesOnClientChange(type,args,obj)
{
	var newDate = YAHOO.artCloud.calendar.cal1.cfg.getProperty("pagedate");;
	calMonth = newDate.getMonth()+1;
	calYear = newDate.getFullYear();

    _getAjaxDates();
}

function _getAjaxDates()
{
    calHighlightDates = null;

    YAHOO.artCloud.calendar.cal1.render();

    // on page init - month and year will be blank and will be filled in by current date or sessions data on server
	var url = '../calendar/calUtil.php?whichCal=' + whichCal + '&month=' + calMonth + '&year=' + calYear;

    var calAjax = new AjaxObj('get', url, _fillHighlightedDates);
}

function _fillHighlightedDates(request)
{
    //reset renderers
    for (x=0;x<=YAHOO.artCloud.calendar.cal1.cellDates.length-1;x++)
    {
        YAHOO.artCloud.calendar.cal1.addRenderer(YAHOO.artCloud.calendar.cal1.cellDates[x][1] + '/' + YAHOO.artCloud.calendar.cal1.cellDates[x][2] + '/' + YAHOO.artCloud.calendar.cal1.cellDates[x][0], YAHOO.artCloud.calendar.cal1.renderCellDefault);
    }

    var xmldoc = request.responseXML;
    var root = xmldoc.getElementsByTagName('root').item(0);
    if (root)
    {
        if (root.getElementsByTagName('month') != null) { calMonth = root.getElementsByTagName('month')[0].firstChild.nodeValue; }
        if (root.getElementsByTagName('year') != null) { calYear = root.getElementsByTagName('year')[0].firstChild.nodeValue; }

        if (calMonth == '') { calMonth = new Date().getMonth() + 1; }
        if (calYear == '') { calYear = new Date().getYear(); }

        if (root.getElementsByTagName('date'))
        {
            calHighlightDates = root.getElementsByTagName('date');

            for (var x=0; x<=calHighlightDates.length-1; x++) { YAHOO.artCloud.calendar.cal1.addRenderer(calHighlightDates[x].firstChild.nodeValue, YAHOO.artCloud.calendar.cal1.renderCellStyleHighlight1); }
        }

        if (root.getElementsByTagName('whichCal') != null) { whichCal = root.getElementsByTagName('whichCal')[0].firstChild.nodeValue; }

        if (root.getElementsByTagName('isin') != null) { isin = root.getElementsByTagName('isin')[0].firstChild.nodeValue; }
        if (isin == "true") { isin = true; }
        else if (isin == "false") { isin = false; }

        if (!isin)
        {
            document.getElementById("cal_full").style.background = "url(../images/cal_bg_nologin.gif) no-repeat";
            document.getElementById("cal_create").style.display = "none";
            document.getElementById("cal_login").style.display = "block";
            document.getElementById("cal_full").style.height = "265px";
            whichCal = "world";
        }
        else if (whichCal == "world")
        {
            document.getElementById("cal_full").style.background = "url(../images/cal_bg_world.gif) no-repeat";
            document.getElementById("cal_create").style.display = "block";
            document.getElementById("cal_login").style.display = "block";
            document.getElementById("cal_full").style.height = "265px";
        }
        else if (whichCal == "my")
        {
            document.getElementById("cal_full").style.background = "url(../images/cal_bg_my.gif) no-repeat";
            document.getElementById("cal_create").style.display = "block";
            document.getElementById("cal_login").style.display = "block";
            document.getElementById("cal_full").style.height = "265px";
        }

        YAHOO.artCloud.calendar.cal1.cfg.setProperty('pagedate', new Date(calYear, calMonth-1, 1), true);
        YAHOO.artCloud.calendar.cal1.render();
    }
}


// event handler for client side date click
function handleCalDateSelect(type,args,obj)
{
	var dates = args[0];
	var date = dates[0];
	var year = date[0], month = date[1], day = date[2];

    window.location = '../calendar/list.php?calType=' + whichCal + '&theDate=' + day + "/" + month + "/" +  year;
}


// client side toggle from world to my calendars and updating server side session
function toggleCal(id)
{
    if (id == "world")
    {
        whichCal = "world";

        var newDate = YAHOO.artCloud.calendar.cal1.cfg.getProperty("pagedate");
        calMonth = newDate.getMonth()+1;
        calYear = newDate.getFullYear();

	    _getAjaxDates();
    }
    else if (id == "my")
    {
        whichCal = "my";

        var newDate = YAHOO.artCloud.calendar.cal1.cfg.getProperty("pagedate");
        calMonth = newDate.getMonth()+1;
        calYear = newDate.getFullYear();

        _getAjaxDates();
    }
}


// event tag functions
function addTags(id)
{
    var divID = 'pnlAddTags';
    var divObj = getElement(divID);
    if(divObj) divObj.style.display = '';

    getElement('lblDescStatus').innerHTML = '';
    
    getCurrentTags(id);

//    arrXY = xy.split(',');
//    var xPos = parseInt(arrXY[0]); // + "px";
//    var yPos = parseInt(arrXY[1]); // + "px";
    var xPos = 240;
    var yPos = 200;

    document.forms['tagForm'].div_event_id.value = id;

    var dialog;
    if(yahooDialogs[divID]){
        dialog = yahooDialogs[divID];
        dialog.show();
        return false;
    }
    else{
        dialog = new YAHOO.widget.Dialog(divID, { postmethod:"async", width:"296px", x:xPos, y:yPos, underlay:"none", draggable:false, fixedcenter:true } );
        yahooDialogs[divID] = dialog;
    }

    var handleSubmit = function() { this.submit(); this.show(); };
    var btnSubmit = [ { text:"Submit", handler:handleSubmit, isDefault:true } ];
    var onFailure = function(obj) {
        displayDialogStatusMessage('lblDescStatus', STATUS_ERROR, 'Your submission failed! Status: ' + obj.status + '!');
    }

    dialog.callback.success = onSuccess;
    dialog.callback.failure = onFailure;

    dialog.cfg.queueProperty("buttons", btnSubmit);
    dialog.render();

    return false;
}

function getCurrentTags(id)
{
    var url = '../calendar/tagUtil.php?do=getTags&id=' + id;
    var calAjax = new AjaxObj('get', url, _fillCurrentTags);
}

function _fillCurrentTags(request)
{
    var xmldoc = request.responseXML;
    var root = xmldoc.getElementsByTagName('root').item(0);
    if (root)
    {
        if (root.getElementsByTagName('tags') && root.getElementsByTagName('tags')[0].firstChild)
        {
             document.forms['tagForm'].tags.value = root.getElementsByTagName('tags')[0].firstChild.nodeValue;
        }
        else
        {
             document.forms['tagForm'].tags.value = "[no current tags for this event]";
        }
    }
}

function onSuccess(obj)
{
    var xmldoc = obj.responseXML;
    var result = false;

    try
    {
        var root = xmldoc.getElementsByTagName('root').item(0);

        if(root.getElementsByTagName("tags")[0].firstChild == null)
        {
            displayDialogStatusMessage('lblDescStatus', STATUS_ERROR, 'Please add at least one tag!');
        }
        else
        {
            var tags = root.getElementsByTagName("tags")[0].firstChild.nodeValue;

            document.forms['tagForm'].tags.value = tags;
            document.forms['tagForm'].new_tags.value = "";

            displayDialogStatusMessage('lblDescStatus', STATUS_SUCCESS, 'Your tags have been added!');
        }
    }
    catch (ex)
    {
        displayDialogStatusMessage('lblDescStatus', STATUS_ERROR, 'There was an error adding your tags! ' + ex.message + '!');
    }
}


// send event functions
function sendMail(id)
{
    getElement('lblDescStatusMail').innerHTML = '';
    document.forms['sendForm'].addresses.value = "";

//    arrXY = xy.split(',');
//    var xPos = parseInt(arrXY[0]);
//    var yPos = parseInt(arrXY[1]);
    var xPos = 200;
    var yPos = 200;

    document.forms['sendForm'].div_send_id.value = id;

    var divID = 'pnlSendMail';
    var divObj = getElement(divID);
    if(divObj) divObj.style.display = '';

    var dialog;
    if(yahooDialogs['pnlSendMail']){
        dialog = yahooDialogs['pnlSendMail'];
        dialog.show();
    }
    else{
        dialog = new YAHOO.widget.Dialog('pnlSendMail', { postmethod:"async", width:296 + "px", x:xPos, y:yPos, underlay:"none", draggable:false, fixedcenter:true } );
        yahooDialogs['pnlSendMail'] = dialog;
    }

    var handleMailSubmit = function() { this.submit(); this.show(); };
    var btnSubmit = [ { text:"Send", handler:handleMailSubmit, isDefault:true } ];
    var onMailFailure = function(obj) {
        displayDialogStatusMessage('lblDescStatusMail', STATUS_ERROR, 'Your email failed. Status: ' + obj.status + '!');
    }

    dialog.callback.success = onMailSuccess;
    dialog.callback.failure = onMailFailure;

    dialog.cfg.queueProperty("buttons", btnSubmit);
    dialog.render();

    return false;
}

function onMailSuccess(obj)
{
    getElement('lblDescStatusMail').innerHTML = '';

    var xmldoc = obj.responseXML;

    try
    {
        var root = xmldoc.getElementsByTagName('root').item(0);
        var error = root.getElementsByTagName("error")[0].firstChild.nodeValue;

        if (error == '[none]')
        {
            document.forms['sendForm'].addresses.value = "";

            displayDialogStatusMessage('lblDescStatusMail', STATUS_SUCCESS, 'This event has been mailed!');
        }
        else
        {
            displayDialogStatusMessage('lblDescStatusMail', STATUS_ERROR, error);
        }
    }
    catch (ex)
    {
        displayDialogStatusMessage('lblDescStatusMail', STATUS_ERROR, 'There was an error sending your mail! ' + ex.message + '!');
    }
}


// get click xy
function getMouseXY(e) {
    var IE = document.all?true:false;
    if (!IE) document.captureEvents(Event.CLICK)

    if (IE) { // grab the x-y pos.s if browser is IE
        tempX = event.x
        tempY = event.y
    }
    else
    {
        tempX = e.screenX
        tempY = e.screenY
    }

    if (tempX < 0){tempX = 0}
    if (tempY < 0){tempY = 0}

    return tempX + ',' + tempY;
}
