var eacwin;
var eventIsLive;
var eventId;
var eventMappingFields;
var loginMode;



Ext.onReady(function() {

    var makeAppointment = Ext.query("*[id^=makeAppointment]");
    
    if(makeAppointment.length > 0)
    {
        eventId = makeAppointment[0].attributes['modalWindowArgs'].value.split(',')[0];
    }
    
    var makeSponsoredAppointment = Ext.query("*[id^=makeSponsoredAppointment]");
    
    if(makeSponsoredAppointment.length > 0)
    {
        eventId = makeSponsoredAppointment[0].attributes['modalWindowArgs'].value.split(',')[0];
    }
    
    Ext.lib.Ajax.defaultPostHeader = 'application/json';

    Ext.Ajax.request({   
        url: '/Connect/Public/AjaxWcfService.svc/GoLiveDate',

        method: 'POST',
        
        params: '{"eventId": ' + eventId + '}',
        
        success: function(response, options) {
            
            eventMappingFields = eval('(' + response.responseText + ')');     
            
            var today = new Date();
            var startDate = parseSerializedDate(eventMappingFields.GoLiveDateResult.StartDate);
            var endDate = parseSerializedDate(eventMappingFields.GoLiveDateResult.EndDate);
            eventIsLive = (startDate < today && today < endDate);      
            getEventVariables();
        }
//        ,
//        
//        failure: function(response, options) {
//            alert(response.responseText);
//        }
        
    });
    
    Ext.Ajax.request({
    
        url: '/Connect/Public/AjaxWcfService.svc/ConnectUserType',
        
        method: 'POST',
        
        success: function(response, options) {
            loginMode = eval('(' + response.responseText + ')');
        }
    });
        
    assignEventsWait();
    
});

function assignEventsWait()
{
    
    //setTimeout('getEventVariables()', 2000);
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);

}

function endRequestHandler(sender, args)
{
    getEventVariables();
}

function getEventVariables()
{
    if(eventId == undefined)
    {
        var makeAppointment = Ext.query("*[id^=makeAppointment]");
        if(makeAppointment.length > 0)
        {
            eventId = makeAppointment[0].attributes['modalWindowArgs'].value.split(',')[0];
        }
    }
    
    Ext.Ajax.request({   
        url: '/Connect/Public/AjaxWcfService.svc/GoLiveDate',

        method: 'POST',
        
        params: '{"eventId": ' + eventId + '}',
        
        success: function(response, options) {
            
            eventMappingFields = eval('(' + response.responseText + ')');     
            
            var today = new Date();
            var startDate = parseSerializedDate(eventMappingFields.GoLiveDateResult.StartDate);
            var endDate = parseSerializedDate(eventMappingFields.GoLiveDateResult.EndDate);
            eventIsLive = (startDate < today && today < endDate);      
            assignEvents();
        }
//        ,
//        
//        failure: function(response, options) {
//            alert(response.responseText);
//        }
        
    });
}


function assignEvents() {

    var makeAppointmentImages = Ext.query("*[id^=makeAppointment]");
    
    for(var i = 0; i < makeAppointmentImages.length; i++)
    {
        var el = Ext.get(makeAppointmentImages[i].id);
        el.on('click', onImageClick);
        
        var elem = document.getElementById(makeAppointmentImages[i].id)
        var x;
        if(elem.attributes['modalWindowArgs'] != null)
        {
            x = elem.attributes['modalWindowArgs'].value.split(',').length;
        }
        if(!eventIsLive)
        {
            elem.src = '../Images/appointmentGrey.gif';
        }
    }
    
    var makeSponsoredAppointmentImages = Ext.query("*[id^=makeSponsoredAppointment]");
    
    for(var i = 0; i < makeSponsoredAppointmentImages.length; i++)
    {
        var el = Ext.get(makeSponsoredAppointmentImages[i].id);
        el.on('click', onImageClick);
        
        var elem = document.getElementById(makeSponsoredAppointmentImages[i].id)
        var x = elem.attributes['modalWindowArgs'].value.split(',').length;
        if(!eventIsLive)
        {
            elem.src = '../Images/appointmentGrey.gif';
        }
    }
    
    var sendMailImages = Ext.query("*[id^=sendMail]");
    
    for(var i = 0; i < sendMailImages.length; i++)
    {
        var el = Ext.get(sendMailImages[i].id);
        el.on('click', onImageClick);
        
        var elem = document.getElementById(sendMailImages[i].id);
        var x = elem.attributes['modalWindowArgs'].value.split(',').length;
        if(!eventIsLive)
        {
            elem.src = '../Images/sendemailGrey.gif';
        }
    }

	var sendSponsoredMailImages = Ext.query("*[id^=sendSponsoredMail]");
    
    for(var i = 0; i < sendSponsoredMailImages.length; i++)
    {
        var el = Ext.get(sendSponsoredMailImages[i].id);
        el.on('click', onImageClick);
        
        var elem = document.getElementById(sendSponsoredMailImages[i].id);
        var x = elem.attributes['modalWindowArgs'].value.split(',').length;
        if(!eventIsLive)
        {
            elem.src = '../Images/sendemailGrey.gif';
        }
    }
    
    var addToExpoImages = Ext.query("*[id^=addToExpo]");
    
    for(var i = 0; i < addToExpoImages.length; i++)
    {
        var el = Ext.get(addToExpoImages[i].id);
        el.on('click', onImageClick);
        
        var elem = document.getElementById(addToExpoImages[i].id);
        var x = elem.attributes['modalWindowArgs'].value.split(',').length;
        if(!eventIsLive)
        {
            elem.src = '../Images/addtoexpoGrey.gif';
        }
    }

	var addSponsoredToExpoImages = Ext.query("*[id^=addSponsoredToExpo]");
    
    for(var i = 0; i < addSponsoredToExpoImages.length; i++)
    {
        var el = Ext.get(addSponsoredToExpoImages[i].id);
        el.on('click', onImageClick);
        
        var elem = document.getElementById(addSponsoredToExpoImages[i].id);
        var x = elem.attributes['modalWindowArgs'].value.split(',').length;
        if(!eventIsLive)
        {
            elem.src = '../Images/addtoexpoGrey.gif';
        }
    }
}

function onImageClick(ev, target)
{
    var args = target.attributes['modalWindowArgs'].value.split(',');
    if(eventMappingFields == null)
    {
        Ext.Ajax.request({   
        url: '/Connect/Public/AjaxWcfService.svc/GoLiveDate',

        method: 'POST',
        
        params: '{"eventId": ' + eventId + '}',
        
        success: function(response, options) {
            
            eventMappingFields = eval('(' + response.responseText + ')');     
            
            var today = new Date();
            var startDate = parseSerializedDate(eventMappingFields.GoLiveDateResult.StartDate);
            var endDate = parseSerializedDate(eventMappingFields.GoLiveDateResult.EndDate);
            eventIsLive = (startDate < today && today < endDate);      
            showContactModal(args[0], args[1], args[2]);
            }
//        ,
//        
//        failure: function(response, options) {
//            alert(response.responseText);
//        }
        
        });
    }
    else
    {
        showContactModal(args[0], args[1], args[2]);
    }
}

function showContactModal(eventId, argument, login)
{
    switch(loginMode.ConnectUserTypeResult)
    {
        case "0":
            if(!eventMappingFields.GoLiveDateResult.StartDate)
            {
                Ext.Msg.show({
                title: 'Hanley Wood Connect',
                msg: notLiveHtml(eventMappingFields.GoLiveDateResult.MarketingName),
                buttons: Ext.Msg.OK
                });
            }
            else
            {
                var today = new Date();
                var startDate = parseSerializedDate(eventMappingFields.GoLiveDateResult.StartDate);
                var endDate = parseSerializedDate(eventMappingFields.GoLiveDateResult.EndDate);
                if(startDate < today && today < endDate)
                {
                	doMessageCenter(argument);
                }
                else
                {
                    Ext.Msg.show({
                    title: 'Hanley Wood Connect',
                    msg: notLiveHtml(eventMappingFields.GoLiveDateResult.MarketingName),
                    buttons: Ext.Msg.OK
                    });
                }
            }
            break;
        case "1":
            if(!login)
            {
                Ext.Msg.show({
                	title: 'Attendees Only',
                	msg: '<br>We are sorry but this feature is not available to exhibitors.<br><br>Only registered attendees are able to make appointments or send email to show exhibitors.',
                	buttons: Ext.Msg.OK
                });
            }
            else
            {
                if(login.indexOf('exhibitor') > -1)
                {
                    if(!eventMappingFields.GoLiveDateResult.StartDate)
                    {
                    Ext.Msg.show({
                        title: 'Hanley Wood Connect',
                        msg: notLiveHtml(eventMappingFields.GoLiveDateResult.MarketingName),
                        buttons: Ext.Msg.OK
                        });
                    }
                    else
                    {
                        var today = new Date();
                        var startDate = parseSerializedDate(eventMappingFields.GoLiveDateResult.StartDate);
                        var endDate = parseSerializedDate(eventMappingFields.GoLiveDateResult.EndDate);
                        if(startDate < today && today < endDate)
                        {
                	        doMessageCenter(argument);
                        }
                        else
                        {
                            Ext.Msg.show({
                                title: 'Hanley Wood Connect',
                                msg: notLiveHtml(eventMappingFields.GoLiveDateResult.MarketingName),
                                buttons: Ext.Msg.OK
                                });
                        }
                    }
                }
            }
            break;
        case "2":
            if(!eventMappingFields.GoLiveDateResult.StartDate)
            {
                Ext.Msg.show({
                title: 'Hanley Wood Connect',
                msg: notLiveHtml(eventMappingFields.GoLiveDateResult.MarketingName),
                buttons: Ext.Msg.OK
                });
            }
            else
            {
                var today = new Date();
                var startDate = parseSerializedDate(eventMappingFields.GoLiveDateResult.StartDate);
                var endDate = parseSerializedDate(eventMappingFields.GoLiveDateResult.EndDate);
                if(startDate < today && today < endDate)
                {
                    Ext.Msg.show({
                    title: 'Hanley Wood Connect',
                    msg: liveHtml(eventMappingFields.GoLiveDateResult.MarketingName, eventMappingFields.GoLiveDateResult.AttendeeLoginUrl, eventMappingFields.GoLiveDateResult.AttendeeRegistrationUrl),
                    buttons: Ext.Msg.OK
                    });
                }
                else
                {
                    Ext.Msg.show({
                    title: 'Hanley Wood Connect',
                    msg: notLiveHtml(eventMappingFields.GoLiveDateResult.MarketingName),
                    buttons: Ext.Msg.OK
                    });
                }
            }
            break;
    }
}
        
function liveHtml(showName, loginUrl, registerUrl)
{
    var html = '<div style="padding: 10px; width: 400px; height: 250px; background-color: white">';
    html += '<img src="../Images/appointment.gif" alt="" />&nbsp;';
    html += '<img src="../Images/sendemail.gif" alt="" />&nbsp;';
    html += '<img src="../Images/addtoexpo.gif" alt="" />&nbsp;';
    html += '<br><h3>You must be signed in to use this feature.</h3>';
    html += '<br><br>Communicate and network with exhibitors before, during and after the show with Connect - our 365 online community for Hanley Wood events.';
    html += '<br><br><h2>REGISTERED ATTENDEES!</h2>';
    html += 'To send emails, make appointments or set up your onsite show itinerary, <a href="' + loginUrl + '?previousPage=' + window.location + '">Sign-In to Connect Now</a> using your eCode.';
    html += '<br><br><h2>NOT YET REGISTERED?</h2>';
    html += '<br>Register for ' + showName + ' and gain access to this innovative and FREE networking solution as part of your registration.';
    html += '<a href="' + registerUrl + '?previousPage=' + window.location + '"><br>REGISTER NOW!</a>';
    return html;
}

function notLiveHtml(showName)
{
    var html = '<div style="padding: 10px; width: 400px; height: 250px; background-color: white">';
    html += '<img src="../Images/appointmentGrey.gif" alt="" />&nbsp;';
    html += '<img src="../Images/sendemailGrey.gif" alt="" />&nbsp;';
    html += '<img src="../Images/addtoexpoGrey.gif" alt="" />&nbsp;';
    html += '<br><h3>This feature is not yet available.</h3>';
    html += '<br><br>Communicate and network with exhibitors before, during and after the show with Connect - our 365 online community for Hanley Wood events.';
    html += '<br><br><h2>COMING SOON!</h2>';
    html += '<br>As registered attendees of ' + showName + ' you will have access to this innovative and FREE networking solution as part of your registration.';
    html += '<br>To send emails, make appointments and set up your onsite show itinerary, you will Sign In using your eCode - a password to be used all your Hanley wood events.';
    html += '<br><br>'
    html += '</div>';
    return html;
}

function parseSerializedDate(serializedDate)
{
    var sd = serializedDate.toString();
    sd = sd.replace('/Date(', '');
    sd = sd.replace(')/', '');
    
    var i = sd.indexOf('-');
    sd = sd.substr(0, i);
    
    i = parseInt(sd, 10);
    
    return new Date(i);   
}

function doMessageCenter(murl)
{

        //var showEventId = document.getElementById("newshow").value;
        Ext.ux.IFrameComponent = Ext.extend(Ext.BoxComponent, {
             onRender : function(ct, position){
                  this.el = ct.createChild({tag: 'iframe', id: 'iframe-'+ this.id, frameBorder: 0, src: this.url});
             }
        });

        //alert(murl)
        var iframe = new Ext.ux.IFrameComponent({ 
                       url:murl
             });
	         
		   eacwin = new Ext.Window({
                 id: 'bogus',                                      
                 title: 'hanleywoodCONNECT',                                                
                 layout: 'fit',                                       
                 width: 850,                                                     
                 height: 700,                                                                                                                                     
                 iconCls: 'bogus',                                              
                 shim:false,                                                    
                 animCollapse:false,                                            
                 constrainHeader:true,
		         closable: true,
		         modal: true,
                 items: iframe
            
           });
           eacwin.show();
		   eacwin.center();
        
}

function MessageCenterCloseWindow()
{	
     eacwin.destroy();
}


