BSD.namespace("BSD.utils.contact_importer");

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

BSD.utils.contact_importer = function(){

    this.contact_importer_step = 1;
    this.default_email_label = contact_importer_dictionary.email_label;
    this.default_password_label = contact_importer_dictionary.password_label;
    this.add_more_callback = "";
    
        
    BSD.utils.contact_importer.show_dialog = function (){

    this.init();
        
    BSD.utils.contact_importer.toggle_scrolling_div_overflow('hidden');
    if(document.getElementById('contact_importer_dialog') && YAHOO.util.Dom.getElementsBy(BSD.utils.contact_importer.test_element,'button','contact_importer_dialog')[0]){
        YAHOO.util.Dom.getElementsBy(BSD.utils.contact_importer.test_element,'button','contact_importer_dialog')[0].innerHTML = contact_importer_dictionary.load_contacts_button_label;
        this.dialog.show();
        this.show_buttons();
        
    } else{
        this.dialog.render(document.body);
    }
    var close_btn = YAHOO.util.Dom.getElementsByClassName('container-close');
    YAHOO.util.Event.addListener(close_btn,"click",BSD.utils.contact_importer.show_scrolling_div_overflow);

    }
    
    BSD.utils.contact_importer.import_address_book = function(){
	var url = "/utils/contact_importer/contact_importer.ajax.php";
	var user = YAHOO.util.Dom.get('webmail_login');
	var pass = YAHOO.util.Dom.get('webmail_password');
	var domain = YAHOO.util.Dom.get('webmail');
	var post_data = "domain="+encodeURIComponent(domain.value)+"&user="+escape(user.value)+"&pass="+escape(pass.value);
    
	var callback =
	{
	  success: function(o) {
	      
	    var results = o.responseText;
	    contact_importer.hide_progressmeter(true);
	    if(results.trim().indexOf("error") == 0){
            //invalid login
            contact_importer.hide_progressmeter(false);
            contact_importer.init();
            var error_div = YAHOO.util.Dom.get('contact_importer_error');
            error_div.innerHTML = contact_importer_dictionary.invalid_login_error;
		
	    } else if(results.trim() == 0){ 
            //nothing in address book
            contact_importer.hide_buttons();
            contact_importer.set_dialog_body("<div id='contact_importer_error'>"+contact_importer_dictionary.no_contacts_error+"</div>");
		
	    } else if(results.trim() == -1){ 
            //nothing in address book
            contact_importer.hide_progressmeter(false);
            contact_importer.init();
            var error_div = YAHOO.util.Dom.get('contact_importer_error');
            error_div.innerHTML = contact_importer_dictionary.generic_error;
		
	    }     

	    else{
            //found an address book
            parsed_results =  eval('(' + results + ')');
            email_results = parsed_results.email;
            name_results = parsed_results.name;
            
            var import_count = email_results.length;
            var instructions = "<div class='results'>"+BSD.blue_dictionary.replace_tokens(contact_importer_dictionary.contacts_loaded_text, {count: import_count}) + " </div>";
            var imported_contacts = "<div id='results_table_header'><p class='input_label'><input type='checkbox' name='select_all' id='select_all' onclick='BSD.utils.contact_importer.toggle_checkboxes()' /> <label for='select_all'>"+contact_importer_dictionary.select_all_label+"</label></p></div><div id='results_table_outer'><div id='contact_importer_scroll'><table cellpadding='0' cellspacing='0' border='0' id='contacts_table'><tbody id='contacts_tbody'>";
            
            for(x=0;x<import_count;x++){
                var identifier = "contact_"+x;
                imported_contacts += "<tr onmouseout='BSD.utils.contact_importer.toggle_bg_color(this,\"#fff\");' onmouseover='BSD.utils.contact_importer.toggle_bg_color(this,\"#eee\");'><td id='cell1'><p class='input_label'><input type='checkbox' name='"+identifier+"' id='"+identifier+"' class='contact_checkbox' value='"+encodeURIComponent(email_results[x])+","+encodeURIComponent(name_results[x])+"' /> <label for='"+identifier+"' style='vertical-align:middle;'>"+name_results[x]+"</label></p></td><td id='cell2'><label for='"+identifier+"'>"+email_results[x]+"</label></td></tr>";
                
            }
            
            imported_contacts += "</tbody></table></div></div>";
            
            BSD.utils.contact_importer.dialog_buttons = ([ { text:contact_importer_dictionary.add_to_invite_label, handler:contact_importer.yes, align:"center" },{ text:contact_importer_dictionary.cancel_label, handler:contact_importer.cancel, align:"center", isDefault:true } ]);
            contact_importer.dialog.cfg.queueProperty("buttons", BSD.utils.contact_importer.dialog_buttons);
        
            contact_importer.set_dialog_body(instructions+imported_contacts);
            
            contact_importer.dialog.render(document.body);
            YAHOO.util.Dom.setStyle("contact_importer_scroll","height",(YAHOO.util.Dom.getViewportHeight()*.4)+"px");
	    }
	    
	  },
	  failure: function(o) {
	      /*failure handler code*/
          contact_importer.hide_progressmeter(false);
          contact_importer.init();
          var error_div = YAHOO.util.Dom.get('contact_importer_error');
          error_div.innerHTML = contact_importer_dictionary.generic_error;
	  },
      timeout: 30000
	}
	
	var transaction = YAHOO.util.Connect.asyncRequest('POST', url, callback, post_data);
	
	// show a status bar during the ajax request
	if(YAHOO.util.Connect.isCallInProgress(transaction)){
	    this.show_progressmeter(contact_importer_dictionary.contacts_loading_text);
	}
    }
    
    BSD.utils.contact_importer.show_progressmeter = function(txt){
	    this.hide_buttons();
	    this.set_dialog_body("<div id='contact_importer_progressmeter_txt'>"+txt+"</div><div id='contact_importer_progressmeter'></div>");    
    
    }
    BSD.utils.contact_importer.hide_progressmeter = function(animate){
	    this.show_buttons();
    }
    BSD.utils.contact_importer.init = function (){
        this.contact_importer_step = 1;
        this.hide_progressmeter(false);

        var instructions = "<span>"+contact_importer_dictionary.form_instructions+"</span><div id='contact_importer_error'></div>";
        var unavailable = "<div id='contact_importer_error'>"+contact_importer_dictionary.unavailable_error+"</div>";
        var select_options;
        
        if(!supported_webmail || supported_webmail.length == 0){
            console.log(supported_webmail);
            this.dialog.setHeader(contact_importer_dictionary.unavailable_header_text); 
            this.set_dialog_body(unavailable);
        } else{
            for(x=0;x < supported_webmail.length;x++){
                select_options += "<option value='"+supported_webmail[x]['file']+":"+supported_webmail[x]['text']+"'>"+supported_webmail[x]['text']+"</option>";
            }
            
            var form = "<table id='contact_importer_login'><tr><td nowrap><strong><label for='webmail_login' id='webmail_login_label'>"+this.default_email_label+"</label></strong></td><td nowrap><input class='input' type='text' name='webmail_login' id='webmail_login' size='18' /> <span style='font-size: 170%; font-weight:bold;'>@</span> <select name='webmail' id='webmail'>"+select_options+"</select></td></tr><tr><td nowrap><strong><label for='webmail_password' id='webmail_password_label'>"+this.default_password_label+"</label></strong></td><td><input class='input' type='password' name='webmail_password' id='webmail_password' size='38' style='width: 225px;'/></td></tr></table>";
            dialog_buttons = ([ { text:contact_importer_dictionary.load_contacts_button_label, handler:this.yes },{ text:contact_importer_dictionary.cancel_label, handler:this.cancel } ]);
            this.dialog.cfg.queueProperty("buttons", dialog_buttons);
            this.dialog.setHeader(contact_importer_dictionary.contact_importer_header); 
            this.set_dialog_body(instructions+form);
        }
    
    }
    
    
    BSD.utils.contact_importer.prototype.handle_yes = function() {

	switch(contact_importer.contact_importer_step){
	    // display imported email addresses
	    case 1:
		if(contact_importer.validate_login()){
		    contact_importer.import_address_book();
		    contact_importer.contact_importer_step++;
		} else{
		    //didnt import anything or login error                
		    return null;
		}
	    break;
	    // set the form fields on the invite page
	    case 2:
    
		var checkboxes = YAHOO.util.Dom.getElementsByClassName('contact_checkbox','input','contacts_tbody');
		contact_importer.show_progressmeter('Loading Contacts. . .');   
		var to = contact_importer.get_email_fields();
		var firstname = contact_importer.get_firstname_fields();
		var lastname = contact_importer.get_lastname_fields();
		var contact_recipient_email = new Array();
		var contact_recipient_firstname = new Array();
		var contact_recipient_lastname = new Array();
		var y = 0;
		
		for(x=0;x<checkboxes.length;x++){
		    
		    if(checkboxes[x].checked){
	
			contact = (checkboxes[x].value).split(",");
			var full_name = decodeURIComponent(contact[1]).split(" ");
			contact_recipient_email[y] = decodeURIComponent(contact[0]);
			contact_recipient_firstname[y] = (full_name[0]) ? full_name[0] : null;
			contact_recipient_lastname[y] = (full_name[1]) ? full_name[1] : null;
			y++;
		    }
		    
		}
	
		if(to){

		    if(to.length == 1 && firstname == ''){ //single to field
		to[0].value += (to[0].value != '') ? ", " : "";
			to[0].value += contact_recipient_email.join(", ");
		       
		    } else{ // multiple to fields
			
			// call the 'addmore' callback to add more 'to' fields
			if(contact_recipient_email.length > to.length){
			    var x = contact_recipient_email.length - to.length;
			    contact_importer_addmore_callback(x);
			    to = contact_importer.get_email_fields();
			    firstname = contact_importer.get_firstname_fields();
			    lastname = contact_importer.get_lastname_fields();
			}
			
			if(contact_recipient_email.length <= to.length){
			    
			    for(x=0;x<contact_recipient_email.length;x++){
				
				to[x].value = decodeURIComponent(contact_recipient_email[x]);
	
				if(firstname[x])
				    firstname[x].value = (contact_recipient_firstname[x]) ? decodeURIComponent(contact_recipient_firstname[x]) : '';
				
				if(lastname[x])
				    lastname[x].value = (contact_recipient_lastname[x]) ? decodeURIComponent(contact_recipient_lastname[x]) : '';                        
			    }
			    
			    
			} else{
                contact_importer.hide_buttons();
                contact_importer.set_dialog_body("<div id='contact_importer_error'>ERROR: Not enough invite fields to import all contacts!</div>");
			}
			
			
			
		    }
		} else{
                contact_importer.hide_buttons();
                contact_importer.set_dialog_body("<div id='contact_importer_error'>ERROR: couldn't find any 'to' fields!</div>");
		}

        contact_importer.dml();
        var success_div_height = Math.round(YAHOO.util.Dom.getViewportHeight()*.6);
        var pad_top = Math.round(success_div_height/3);
		contact_importer.set_dialog_body("<div style='text-align:center; font-size: 150%; font-weight: bold; height: "+success_div_height+"px;vertical-align: middle;padding-top:"+pad_top+"px;'>"+contact_importer_dictionary.success_message+"</div>");
        setTimeout("YAHOO.util.Dom.setStyle('contact_importer_scroll','display','none');contact_importer.dialog.hide();contact_importer.toggle_scrolling_div_overflow('auto');",2000);
	    break;
    
	}
    }
    
    BSD.utils.contact_importer.prototype.handle_no = function() {
        BSD.utils.contact_importer.toggle_scrolling_div_overflow('auto');
        this.hide();
    }
    
    BSD.utils.contact_importer.get_email_fields = function(){
        var to = YAHOO.util.Dom.getElementsByClassName('contact_importer_email');
        var to_array = new Array();
        if(to.length == 1)
            return to;
        else{
            var y = 0;
            for(x=0;x<to.length;x++){
                if(to[x].value == ''){
                    to_array[y] = to[x];
                    y++;
                }
            }
            
            return to_array;
            
        }
    }
    
    BSD.utils.contact_importer.get_firstname_fields = function(){
        var firstname = YAHOO.util.Dom.getElementsByClassName('contact_importer_firstname');
        var to = YAHOO.util.Dom.getElementsByClassName('contact_importer_email');
        var firstname_array = new Array();
        if(firstname.length == 1)
            return firstname;
        else{
            var y = 0;
            for(x=0;x<firstname.length;x++){
                if(firstname[x].value == '' && to[x].value == ''){
                    firstname_array[y] = firstname[x];
                    y++;
                }
            }
            
            return firstname_array;
            
        }
    }
    
    BSD.utils.contact_importer.get_lastname_fields = function(){
        var lastname = YAHOO.util.Dom.getElementsByClassName('contact_importer_lastname');
        var to = YAHOO.util.Dom.getElementsByClassName('contact_importer_email');
        var lastname_array = new Array();
        if(lastname.length == 1)
            return lastname;
        else{
            var y = 0;
            for(x=0;x<lastname.length;x++){
                if(lastname[x].value == '' && to[x].value == ''){
                    lastname_array[y] = lastname[x];
                    y++;
                }
            }
            
            return lastname_array;
            
        }
    }
    
    BSD.utils.contact_importer.toggle_checkboxes = function(){
	var select_all = YAHOO.util.Dom.get('select_all');
	var checkboxes = YAHOO.util.Dom.getElementsByClassName('contact_checkbox','input','contacts_tbody');
    
	for(x=0;x<checkboxes.length;x++){
	    
	    checkboxes[x].checked = (select_all.checked) ? true : false;
	    
	}
	
    }
    
    BSD.utils.contact_importer.show_dialog_buttons = function(){    
	var buttons = YAHOO.util.Dom.getElementsByClassName('ft', 'div', 'contact_importer_dialog');
	YAHOO.util.Dom.setStyle(buttons[0],'visibility','');    
    }
    
    BSD.utils.contact_importer.hide_dialog_buttons = function(){    
	var buttons = YAHOO.util.Dom.getElementsByClassName('ft');
	YAHOO.util.Dom.setStyle(buttons[0],'visibility','hidden');    
    }
    BSD.utils.contact_importer.validate_login = function(){
	
	var email = YAHOO.util.Dom.get('webmail_login');
	var password = YAHOO.util.Dom.get('webmail_password');
	var e_label = YAHOO.util.Dom.get('webmail_login_label');
	var p_label = YAHOO.util.Dom.get('webmail_password_label');
	var error = false;

	if(email && password){
	    
	    if(email.value == ''){
		error = true;
		e_label.innerHTML = this.default_email_label+"<br /><span style='color:red;font-size: 95%;'>"+contact_importer_dictionary.required_error+"</span>";
	    }
	    
	    if(password.value == ''){
		error = true;
		p_label.innerHTML = this.default_password_label+"<br /><span style='color:red;font-size: 95%;'>"+contact_importer_dictionary.required_error+"</span>";
	    }
	    
	    if(error){
		return false;
	    } else{
		
		return true;
		e_label = this.default_email_label;
		p_label = this.default_password_label;
	    }
	    
	    
	}
	
    }
    BSD.utils.contact_importer.toggle_bg_color = function(el,color){
	el.style.backgroundColor = color;
    }
    BSD.utils.contact_importer.set_body = function(content){
	    var wrapper = "<div id='contact_importer_wrapper'>"+content+"</div>";
	    this.dialog.setBody(wrapper);
    }

    BSD.utils.contact_importer.test_element = function(el){
        if(YAHOO.util.Dom.get(el))
            return true;
        else
            return false;
        
    }
    

    BSD.utils.contact_importer.dml = function(){
        
        var df = YAHOO.util.Dom.get('bsd_drl');
        if(df)
                df.value = 1;
    }
    
    BSD.utils.contact_importer.show_scrolling_div_overflow = function(){
        var to_field = contact_importer.get_email_fields();
        
        if(to_field.length == 1)
                to_field[0].style.overflow = "auto";
        
        if(YAHOO.util.Dom.get('invite_table'))
            YAHOO.util.Dom.setStyle('invite_table','overflow',"auto");
    }
    
    
    
    BSD.utils.contact_importer.toggle_scrolling_div_overflow = function(overflow){
        var to_field = this.get_email_fields();
        
        if(to_field.length == 1)
                to_field[0].style.overflow = overflow;
        
        if(YAHOO.util.Dom.get('invite_table'))
            YAHOO.util.Dom.setStyle('invite_table','overflow',overflow);
    }
    
    // simpledialog definition
    this.dialog = new YAHOO.widget.SimpleDialog("contact_importer_dialog", {  
	    width: "54em",  
	    height: (YAHOO.util.Dom.getViewportHeight()*.67)+"px",
	    effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.25},  
	    fixedcenter:true, 
	    modal:true,
      zIndex: 100000,
      autofillheight: null,
	    draggable:false
    });

    this.show_dialog = BSD.utils.contact_importer.show_dialog;
    this.import_address_book = BSD.utils.contact_importer.import_address_book;
    this.show_progressmeter = BSD.utils.contact_importer.show_progressmeter;
    this.hide_progressmeter = BSD.utils.contact_importer.hide_progressmeter;
    this.init = BSD.utils.contact_importer.init;
    this.yes = BSD.utils.contact_importer.prototype.handle_yes;
    this.cancel = BSD.utils.contact_importer.prototype.handle_no;
    this.get_email_fields = BSD.utils.contact_importer.get_email_fields;
    this.get_firstname_fields = BSD.utils.contact_importer.get_firstname_fields;
    this.get_lastname_fields = BSD.utils.contact_importer.get_lastname_fields;
    this.toggle_checkboxes = BSD.utils.contact_importer.toggle_checkboxes;
    this.show_buttons = BSD.utils.contact_importer.show_dialog_buttons;
    this.hide_buttons = BSD.utils.contact_importer.hide_dialog_buttons;
    this.validate_login = BSD.utils.contact_importer.validate_login;
    this.toggle_bg_color = BSD.utils.contact_importer.toggle_bg_color;
    this.set_dialog_body = BSD.utils.contact_importer.set_body;
    this.dml =  BSD.utils.contact_importer.dml;
    this.toggle_scrolling_div_overflow = BSD.utils.contact_importer.toggle_scrolling_div_overflow;
    
}
var contact_importer;
YAHOO.util.Event.addListener(window, "load",function(){ contact_importer = new BSD.utils.contact_importer(); });
