/* SET UP MAIN NAV **********************************************************
 * Desc: 
 *  > Wires up the anchors to the li elements in the main nav.
 ****************************************************************************/
window.addEvent('domready', function initMainNav(){
    // Anchor up the main nav
    $$('li.js-main-nav').each(function(el){
    	el.addEvent('click', function(e){
    		new Event(e).stop();
            href = el.getProperty('href');
    		location.href=href;
    	});
    });    
});



/* TOGGLE *******************************************************************
 * Desc: 
 *  > Toggles an element between its hidden and displayed state.
 ****************************************************************************/
function toggle(div){
    if($(div).hasClass("dn")){
        $(div).removeClass("dn");
    }
    else{
        $(div).addClass("dn");
    }
}




/* SUBMIT POST **************************************************************
 * Desc: 
 *  > Ajax way to submit a post in the forums.
 ****************************************************************************/
function submitPost(input_text, topic_id, div_to_update, div_processing){
    if($(input_text).value == '')
        alert('You must enter some text to post.');
    else{
        
        $(div_processing).removeClass('dn');

        var data = {'body' : $(input_text).value, 'topic_id':topic_id};
    
        // Make a json request to update the field value
    	new Json.Remote('/forums/submit-post/', {
    	    method: 'post',
    	    onComplete: function(response){
    	        if(response.success){
    	            $(div_processing).addClass('dn');
    	            $(div_to_update).innerHTML = response.html;
    	        }
    	        else{
    	            alert('Could not save correctly - please try again.');
    	        }
    	    }
    	}).send(data);
    }
}




/* ADD MAJOR ***************************************************************
 * Desc:
 *  > Test files command to ajax submit a new major.
 ***************************************************************************/
function addMajor(input_text, div_to_update, div_processing){
    if($(input_text).value == '')
        alert('You must enter some text.');
    else{

        $(div_processing).removeClass('dn');

        var data = {'name' : $(input_text).value};
    
        // Make a json request to update the field value
    	new Json.Remote('/test-files/submit-major/', {
    	    method: 'post',
    	    onComplete: function(response){
    	        if(response.success){
    	            $(div_processing).addClass('dn');
    	            $(div_to_update).innerHTML = response.html;
    	        }
    	        else{
    	            alert('Could not save correctly - please try again.');
    	        }
    	    }
    	}).send(data);
    }    
}



/* ADD COURSE **************************************************************
 * Desc:
 *  > Test files command to ajax submit a new course.
 ***************************************************************************/
function addCourse(input_text, select_input, div_to_update, div_processing){
    if($(input_text).value == '')
        alert('You must enter some text.');
    else{

        $(div_processing).removeClass('dn');

        var data = {'name' : $(input_text).value, 'major': $(select_input)[$(select_input).selectedIndex].value};
    
        // Make a json request to update the field value
    	new Json.Remote('/test-files/submit-course/', {
    	    method: 'post',
    	    onComplete: function(response){
    	        if(response.success){
    	            $(div_processing).addClass('dn');
    	            $(div_to_update).innerHTML = response.html;
    	        }
    	        else{
    	            alert('Could not save correctly - please try again.');
    	        }
    	    }
    	}).send(data);
    }    
}



/* CENTERED POPUP **********************************************************
 * Desc:
 *  > Launches a centered popup for image details.
 ***************************************************************************/
var win = null;
function centeredPopUp(new_page, new_name, w, h, features){
    var winl = (screen.width-w)/2;
    var wint = (screen.height-h)/2;
    if (winl < 0) winl = 0;
    if (wint < 0) wint = 0;
    var settings = 'height=' + h + ',';
    settings += 'width=' + w + ',';
    settings += 'top=' + wint + ',';
    settings += 'left=' + winl + ',';
    settings += 'location=0,';
    settings += features;
    win = window.open(new_page,new_name,settings);
    win.window.focus();    
}




/* EDIT EXTERNAL CONTENT ***************************************************
 * Desc:
 *  > Allows staff to edit external content.
 ***************************************************************************/
var contentEditManager = new Class({
    
    initialize: function(options){
        // External Content Chunks
        this.wireAddClickEvents();
        this.wireEditClickEvents();
        this.wireDeleteClickEvents();
        
        // Famous Alumni Chunks
        this.wireAddAlumniClickEvents();
        
        // Contact Info Chunks
        this.wireContactInfoClickEvents();
        
    },
    
    wireAddClickEvents: function(){
        $$('a.js-add-content').each(function(el){
            el.addEvent('click', function(e){
                $('initial-content').addClass('dn');
                $('edit-content').removeClass('dn');
            });
        }.bind(this));
    },
    
    wireEditClickEvents: function(){
        $$('a.js-edit-content').each(function(el){
            el.addEvent('click', function(e){
                var object_id = el.getProperty('object_id');
                var ct_id = el.getProperty('ct_id');
                
                // Fetch the text wrapper and hide that div
                $('js-text-' + object_id).addClass('dn');
                $('js-form-' + object_id).removeClass('dn');
            });
        }.bind(this));
    },
    
    wireDeleteClickEvents: function(){
        $$('a.js-delete-content').each(function(el){
            el.addEvent('click', function(e){
                var object_id = el.getProperty('object_id');
                var ct_id = el.getProperty('ct_id');
                
                // Have the user confirm that they want to delete this text
                var c = confirm('Are you sure you want to delete this text? This action cannot be undone.');
                if (c){
                    // Send a request to delete the content
                    location.href = '/delete-content/?object_id=' + object_id + '&ct_id=' + ct_id;
                }
            });
        }.bind(this));
    },
    
    wireAddAlumniClickEvents: function(){
        $$('a.add-alumni').each(function(el){
            el.addEvent('click', function(e){
                $('add-new-famous-alumni').removeClass('dn');
                $('add-new-famous-alumni-link').addClass('dn');
            });
        });
    },
    
    wireContactInfoClickEvents: function(){
        $$('a.edit-contact-info').each(function(el){
            el.addEvent('click', function(e){
                $('edit-contact-info').removeClass('dn');
                $('edit-contact-info-link').addClass('dn');
            });
        });
        $$('input.cacnel-contact-info').each(function(el){
            el.addEvent('click', function(e){
                $('edit-contact-info').addClass('dn');
                $('edit-contact-info-link').removeClass('dn');
            });
        });
        
    }
});
contentEditManager.implement(new Events);
contentEditManager.implement(new Options);







/* EDIT EXTERNAL CONTENT ***************************************************
 * Desc:
 *  > Allows staff to edit external content.
 ***************************************************************************/
var regFormManager = new Class({
    
    initialize: function(){
        // Wire input checkboxes
        this.wireDomainCheck();
        this.wireEmailCheck();
    },
    
    wireDomainCheck: function(){
        $('id_subdomain_name').addEvent('blur', function(e){
            
            // If we have a valid value in here - check db to see if the domain is already taken.
            if($('id_subdomain_name').value != ''){
                var data = {'field':'subdomain_name', 'value':$('id_subdomain_name').value};

                // Make a json request to check the value
                new Json.Remote('/register/validate-data/', {
                    method: 'post',
                    onComplete: function(response){
                        if(response.is_valid){
                            $('js-subdomain_name').innerHTML = 'Valid';
                        }
                        else{
                            $('js-subdomain_name').innerHTML = '<span style="color:red;">Already Taken</span>';
                        }
                    }
                }).send(data);
            }
        });       
    },
    
    wireEmailCheck: function(){
        $('id_email').addEvent('blur', function(e){
            
            if(isValidEmail($('id_email').value)){
                // If we have a valid value in here - check db to see if the domain is already taken.
                if($('id_email').value != ''){
                
                    var data = {'field':'email', 'value':$('id_email').value};

                    // Make a json request to check the value
                    new Json.Remote('/register/validate-data/', {
                        method: 'post',
                        onComplete: function(response){
                            if(response.is_valid){
                                $('js-email').innerHTML = 'Valid';
                            }
                            else{
                                $('js-email').innerHTML = '<span style="color:red;">Already Taken</span>';
                            }
                        }
                    }).send(data);
                }
            }
            else{
                alert('Please Enter A Valid Email')
            }
        });
        
        $('id_email').addEvent('focus', function(e){
            $('js-email').innerHTML = '';
        });
    }
});
regFormManager.implement(new Events);
regFormManager.implement(new Options);





/* CHATTER APP *************************************************************
 * Desc:
 *  > Manages the chatter app.
 ***************************************************************************/
var chatterManager = new Class({
    
    initialize: function(){

        // Wire Events if there is a main POST body on the page.
        if($('js-post-body')){
            $('js-post-body').value = '';
            this.wirePostButton();
        }
        
        // Wire click events
        this.wireReplyButton();
        this.wireLikeButton();
        this.wireBookmarkButton();
    },
    
    _sendPostData: function(body, inject_div, data){
        if(body == ''){
            alert('Please enter some text.');
        }
        else{            
            // Make a json request to check the value
            new Json.Remote('/discussion/process-statement/', {
                method: 'post',
                onComplete: function(response){
                    if(response.error){
                        alert(error)
                    }
                    else{
                        // Create a new div and stuff the response html into it
                        var newdiv = new Element('div');
                        newdiv.innerHTML = response.html;
                    
                        // Inject this div into the listener
                        newdiv.injectTop(inject_div);
                        if(inject_div.hasClass('dn')){
                            inject_div.removeClass('dn');
                        }
                    
                        var original_bg = '';
                        var parent = newdiv;
                        while(parent && (parent.getStyle('background-color') == '' || parent.getStyle('background-color') == 'transparent')){
                            parent = parent.getParent();
                        }
                        if(parent)
                            original_bg = parent.getStyle('background-color');
                        
                        var styleFx = new Fx.Styles(newdiv);
                        styleFx.start({'background-color':'#888', 'duration':1600}).chain(function(){
                            styleFx.start({'background-color':original_bg, 'duration':1600});
                        });
                    }
                }
            }).send(data);
        }
    },
    
    wirePostButton: function(){
        $('js-post-btn').addEvent('click', function(e){
            
            var statement_group_id = $('statement_group_id')[$('statement_group_id').selectedIndex].value;
            var body = $('js-post-body').value;
            
            this._sendPostData(body, $('js-new-statement'), {'body':encodeString(body), 'statement_group_id':statement_group_id});
            
        }.bind(this));
    },
        
    wireReplyButton: function(){
        
        // Add click event to display the form
        $$('a.js-reply').each(function(el){
            el.addEvent('click', function(e){
                var statement_id = el.getProperty('id');
                $("js-reply-container-" + statement_id).removeClass('dn');
            });
        });
        
        // Add click event for a form post
        $$('input.js-btn-reply').each(function(el){
            el.addEvent('click', function(e){

                var statement_id = el.getProperty('statement_id');
                var body = $('js-reply-' + statement_id).value;
                var reply_div = $('js-chatter-reply-container-div-' + statement_id);
                
                this._sendPostData(body, reply_div, {'body':encodeString(body), 'statement_id':statement_id, 'tpl':'chatter/pods/reply.html'});
                                
            }.bind(this));
        }.bind(this));
    },
    
    wireBookmarkButton: function(){
        $$('a.js-bookmark').each(function(el){
            el.addEvent('click', function(e){
                this._sendData({'statement_id':el.getProperty('statement_id')}, '/discussion/process-bookmark/', el);
            }.bind(this));
        }.bind(this));
    },

    wireLikeButton: function(){
        
        $$('a.js-like').each(function(el){
            el.addEvent('click', function(e){
                this._sendData({'statement_id':el.getProperty('statement_id')}, '/discussion/process-like/', el);
            }.bind(this));
        }.bind(this));
    },
    
    _sendData: function(data, url, el){
        // Make a json request to 'like' the statement
        new Json.Remote(url, {
            method: 'post',
            onComplete: function(response){
                if(response.error){
                    alert(error);
                }
                else{
                    el.innerHTML = response.text;
                }
            }
        }).send(data);

    }
});
chatterManager.implement(new Events);
chatterManager.implement(new Options);







/* VALIDATE EMAIL **********************************************************
 * Desc:
 *  > Checks whether or not an email submitted is valid.
 ***************************************************************************/
function isValidEmail(str){
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}


/* ENCODE STRING  **********************************************************
 * Desc:
 *  > Encodes a string to make it safe.
 ***************************************************************************/
function encodeString(str) {
    return str.replace(/;/g, '%3B').replace(/&/g, '%26');
}
