Ext.BLANK_IMAGE_URL = '/common/themes/2008/images/blank.gif';
Ext.SSL_URL         = '/common/blank.html';

function show_login_form()
{
    //show_dialog('login');
    u_login();
}


function login_user(context, dialog)
{
    /* RegEx Patterns */
    var emailPattern    = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/;
    var emails          = document.getElementsByName('email');
    var passwords       = document.getElementsByName('password');
    var remember_mes    = document.getElementsByName('remember_me');
    var login_forms     = document.getElementsByName('login_form');

    var email_index;
    var pwd_index;
    var remember_index;

    if (login_forms.length > 1)
    {
        if (login_forms[0] == context)
        {
            email_index = 0;
            pwd_index = 0;
            remember_index = 0;
        }
        else
        {
            email_index = 1;
            pwd_index = 1;
            remember_index = 1;
        }
    }
    else if (document.URL.indexOf('/subscribe.php') >= 0 || document.URL.indexOf('/sponsor_reg') >= 0)
    {
        email_index = 1;
        pwd_index = 0;
        remember_index = 0;
    }
    else
    {
        email_index = 0;
        pwd_index = 0;
        remember_index = 0;
    }
    var email       = emails[email_index];
    var password    = passwords[pwd_index];
    var remember_me = remember_mes[remember_index];

    var callback;
    if (email && !emailPattern.test(email.value))
    {
        callback =  function()
        {
            email.focus();
        };
        Ext.MessageBox.alert('Invalid Input', 'Please enter a valid email address', callback);
        return false;
    }
    else if (!email)
    {
		email = document.getElementById('email');
	}

    if (password.value == "" || password.value == " ")
    {
        callback =  function()
        {
            password.focus();
        };
        Ext.MessageBox.alert('Invalid Input', 'Please enter your password', callback);

        return false;
    }

    var params = new Object();

    params['email']         = email.value;
    params['password']      = password.value;
    params['remember_me']   = remember_me.checked;
    params['func']          = 'login_user';
    
    Ext.MessageBox.show({title: 'Please wait...', msg: 'Logging in...', width:240, closable:false});

	Ext.Ajax.request({
		url: '/common/ajax/login.php',
		success: function(o)
		{
		    var firstName = o.responseText;
		
		    //firstName being greater than zero means the user is active and the login was a success
		    if (0 == firstName)
		    {
		        Ext.MessageBox.alert('Login Problem', 'Invalid account');
		    }
		    else if (-1 == firstName)
		    {
		        Ext.MessageBox.alert('Login Problem',
		            'Your account has not been activated. ' +
		            'Please follow the directions in the activation email that was sent to ' + email.value);
		    }
		    else if (document.URL.indexOf('/briefcase') >= 0 || document.URL.indexOf('/articles') >= 0)
		    {
		        window.location.reload();
		        return;
		    }
		    else if (document.URL.indexOf('/events') >= 0 ||
		             document.URL.indexOf('/subscribe') >= 0 ||
		             document.URL.indexOf('/dc') >= 0 ||
		             //Total hack, but no time to abstract all of these redirects out... -Kavih
		             document.URL.indexOf('/gt/123583') >= 0 ||
		             document.URL.indexOf('/resource') >= 0 ||
		             document.URL.indexOf('/enl_subscribe') >= 0 ||
		             document.URL.indexOf('/topic') >= 0 ||
		             document.URL.indexOf('/em') >= 0)
		    {
	            window.location.href = window.location.pathname + window.location.search;
		
		        return;
		    }
		    else if(document.URL.indexOf('/ul/') >= 0)
		    {
		        window.location.href = '/gt/';
		    }
		    else
		    {
		        Ext.get('salutation').dom.innerHTML = 'Welcome, ' + firstName;
		
		        Ext.get('login_box').dom.style.display  = 'none';
		        Ext.get('logout_box').dom.style.display = '';
		        //Ext.get('btn_briefcase').dom.href       = '/briefcase';
		
		        dialog.hide();
		        Ext.MessageBox.hide();
		    }
		},
		params: params
	});
}


function logout_user()
{
    var params = new Object();

    params['func'] = 'logout_user';

    Ext.MessageBox.show({title: 'Please wait...', msg: 'Logging out...', width:240, closable:false});

    Ext.Ajax.request({
        url: '/common/ajax/login.php',
        success: function(o)
        {
	        var logout = o.responseText;
	
	        //Successful logout
	        if (1 == logout)
	        {
	            if (document.URL.indexOf('/articles') >= 0 || document.URL.indexOf('/briefcase') >= 0)
	            {
	                window.location.reload();
	                return;
	            }
	            else if (document.URL.indexOf('/events') >= 0 ||
	                     document.URL.indexOf('/subscribe') >= 0 ||
	                     document.URL.indexOf('/dc') >= 0 ||
	                     //Total hack, but no time to abstract all of these redirects out... -Kavih
	                     document.URL.indexOf('/gt/123583') >= 0 ||
	                     document.URL.indexOf('/resource') >= 0 ||
	                     document.URL.indexOf('/enl_subscribe') >= 0 ||
	                     document.URL.indexOf('/topic') >= 0 ||
	                     document.URL.indexOf('/em') >= 0)
	            {
                    window.location.href = window.location.pathname + window.location.search;
	
	                return;
	            }
	            else
	            {
	                Ext.get('salutation').dom.innerHTML     = '';       // blank out name for privacy
	                Ext.get('logout_box').dom.style.display = 'none';
	                Ext.get('login_box').dom.style.display  = '';
	                
	                //Ext.get('btn_briefcase').dom.href       = 'javascript:show_dialog(\'briefcase_not_logged_in\');';
	            }
	        }
	
	        Ext.MessageBox.hide();
	    },
        params: params
    });
}


function confirm_password_reset(email)
{
    Ext.Msg.confirm(
        'Password Reset',
        '<b>Would you like to reset your password?</b><br/>An email will be sent to ' +email+ 
            ' with a new temporary password.',
        function(btn, text)
        {
            if ('yes' == btn)
            {
                reset_password(email);
            }
        }
    ); 
}


function reset_password(email)
{
    var params = new Object();
    
    params['email'] = email;
    params['force'] = true;

    Ext.MessageBox.show({title: 'Processing', msg: 'Processing your request...', width:240, closable:false});
    
    Ext.Ajax.request({
        url: '/ul/recover.php',
        success: function(o)
        {
	        var result = Ext.util.JSON.decode(o.responseText);
	        
	        Ext.MessageBox.hide();
	        
	        if (! (result instanceof Object))
	        {
	            Ext.Msg.alert('Unknown Error', result);
	        }
	        else if (result.data.error_message.length > 0)
	        {
	            Ext.Msg.alert('Error', result.data.error_message);
	        }
	        else
	        {
	            Ext.Msg.alert('Password Reset', 'Your password has been reset. Check your email account for your new password.');
	        }
        },
        params: params
    });
}


function show_email_form(pk, type, title)
{
    show_dialog('email', {title: 'Email this ' + type + ' to a colleague'}, {pk: pk,  title: title});
}


function send_email(context, dialog)
{
    /* RegEx Patterns */
    var emailPattern    = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/;
    var dest_emails     = Ext.get('dest_email').dom.value.split(',');

    var callback;
    if (!emailPattern.test(Ext.get('source_email').dom.value))
    {
        callback =  function()
        {
            Ext.get('source_email').dom.focus();
        };
        Ext.MessageBox.alert('Invalid Input', 'Your email address is not valid', callback);
        return false;
    }

    if (!emailPattern.test(dest_emails[0]))
    {
        callback =  function()
        {
            Ext.get('dest_email').dom.focus();
        };
        Ext.MessageBox.alert('Invalid Input', 'Please enter a valid destination email address', callback);
        return false;
    }

    for (var i = 1; i < dest_emails.length; i++)
    {
        if (!emailPattern.test(dest_emails[i]))
        {
            callback =  function()
            {
                Ext.get('dest_email').dom.focus();
            };
            Ext.MessageBox.alert('Invalid Input', 'One of the destination email addresses is not valid', callback);
            return false;
        }
    }

    var params = new Object();

    params['pk']            = context.pk;
    params['title']         = context.title;
    params['src_email']     = Ext.get('source_email').dom.value;
    params['dest_email']    = Ext.get('dest_email').dom.value;
    params['comments']      = Ext.get('comments').dom.value;
    params['func']          = 'email_item';

    Ext.get('email_form_content').hide();
    Ext.get('email_form_content').setDisplayed('none');
    Ext.get('emailing').show();

    Ext.Ajax.request({
        url: '/common/ajax/email.php',
        success: function(o)
        {
	        var email_status = o.responseText;
	
	        //Successful email
	        if (1 == email_status)
	        {
	            Ext.get('emailing').setDisplayed('none');
	            Ext.get('emailing').hide();
	            Ext.MessageBox.alert('Email Success', 'Your email has been sent successfully!');
	            dialog.hide();
	        }
	        else
	        {
	            Ext.MessageBox.alert('Email Error', 'Unfortunately we were unable to send the email!');
	            Ext.get('email_form_content').show();
	        }
        },
        params: params
    });
}


function show_comment_form(pk, type)
{
    show_dialog('comment', {title: 'Post a comment for this ' + type}, pk);
}


function create_comment(pk, dialog)
{
    /* RegEx Patterns */
    var emailPattern = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/;

    var callback;
    if ((document.getElementById('dialog_comment_title').value == ""
        || document.getElementById('dialog_comment_title').value == " "
        || document.getElementById('dialog_comment_title').value == "Choose..."))
    {
        callback =  function()
        {
            Ext.get('dialog_comment_title').dom.focus();
        };
        Ext.MessageBox.alert('Invalid Input', 'Please enter a comment title', callback);
        return false;
    }

    if ((document.getElementById('dialog_comment_text').value == ""
        || document.getElementById('dialog_comment_text').value == " "
        || document.getElementById('dialog_comment_text').value == "Choose..."))
    {
        callback =  function()
        {
            Ext.get('dialog_comment_text').dom.focus();
        };
        Ext.MessageBox.alert('Invalid Input', 'Please enter your comment text', callback);

        return false;
    }

    var params = new Object();

    params['node_pk']       = pk;
    params['title']         = Ext.get('dialog_comment_title').dom.value;
    params['text']          = Ext.get('dialog_comment_text').dom.value;
    params['func']          = 'add_comment';

    Ext.get('comment_form_content').hide();
    Ext.get('comment_form_content').setDisplayed('none');
    Ext.get('commenting').show();

    Ext.Ajax.request({
        url: '/common/ajax/comments.php',
        success: function(o)
        {
	        var comment_status = o.responseText;
	
	        //Successful comment
	        if (comment_status.indexOf('successfully') >= 0)
	        {
	            Ext.get('commenting').setDisplayed('none');
	            Ext.get('commenting').hide();
	            Ext.MessageBox.alert('Comment Post Success', 'Your comment has been posted successfully!');
	            dialog.hide();
	        }
	        else
	        {
	            Ext.MessageBox.alert('Comment Post Error', 'Unfortunately we were unable to post the comment!');
	            Ext.get('comment_form_content').show();
	        }
        },
        params: params
    });
}


/**SHOPPING CART FUNCTIONS**/
function get_query_string(key)
{
    var search_parts = window.location.search.substring(1).split('&');

    var key_values  = new Object();
    for(var i = 0; i < search_parts.length; i++)
    {
        var key_value = search_parts[i].split('=');
        key_values[key_value[0]] = key_value[1];
    }

    return key_values[key];
}

function add_to_cart(pk, event_root_pk)
{
    Ext.MessageBox.show({title: 'Please wait...', msg: 'Updating your shopping cart...<br/>', width:240, closable:false});

    var params = new Object();

    params['pk']            = pk;
    params['event_root_pk'] = event_root_pk;
    params['func']          = 'add_to_cart';

    Ext.Ajax.request({
        url: '/common/ajax/shopping_cart.php',
        success: function(o)
        {
	        if (false == o.responseText || 'duplicate' == o.responseText || 'schedule conflict' == o.responseText 
	            || 'not enrollable' == o.responseText)
	        {
	            Ext.MessageBox.hide();
	            switch (o.responseText) {
	                case 'duplicate':
	                    Ext.MessageBox.alert('Error', 'The item is already in the cart.');
	                    break;
	                case 'schedule conflict':
	                    Ext.MessageBox.alert('Error', 'There is a schedule conflict with the item in the cart.');
	                    break;
	                case 'not enrollable':
	                    Ext.MessageBox.alert('Error', 'The selected item is not enrollable at this time.');
	                    break;
	                default:
	                    Ext.MessageBox.alert('Error', 'There was an error adding this item to your cart.');
	            }
	        }
	        else
	        {
	            // Get the shopping cart element
	            var el  = Ext.get('cart-contents');
	            var mgr = el.getUpdateManager();
	            mgr.update("/common/ajax/shopping_cart.php", "event_root_pk="+event_root_pk+
	                                                                     "&func=get_cart");
	            mgr.on('update', function(){
	                Ext.MessageBox.hide();
	            })
	        }
        },
        params: params
    });
}

function remove_from_cart(pk, event_root_pk)
{
    Ext.MessageBox.show({title: 'Please wait...', msg: 'Updating your shopping cart...<br/>', width:240, closable:false});

    var params = new Object();

    params['pk']            = pk;
    params['event_root_pk'] = event_root_pk;
    params['func']          = 'remove_from_cart';

    Ext.Ajax.request({
        url: '/common/ajax/shopping_cart.php',
        success: function(o)
        {
	        if (false == o.responseText)
	        {
	            Ext.MessageBox.hide();
	            Ext.MessageBox.alert('Error', 'There was an error adding this item to your cart.');
	        }
	        else
	        {
	            // Get the shopping cart element
	            var el  = Ext.get('cart-contents');
	            var mgr = el.getUpdateManager();
	            mgr.update("/common/ajax/shopping_cart.php", "event_root_pk="+event_root_pk+
	                                                                     "&func=get_cart");
	            mgr.on('update', function(){
	                Ext.MessageBox.hide();
	            })
	        }
        },
        params: params
    });
}

function get_events_form(el, module, event_root_pk)
{
    Ext.get(el).load({
        url: "/common/ajax/forms.php",
        scripts: true,
        params: 'pfunc=get_events_form&module='+module+'&event_root_pk='+event_root_pk,
        text: "Loading Form..."
   });
}
