/**
 * 
 */

function updateNodes(nodes, index) {
    nodes.each(
        function(node) {
            if (node.id != '') {
                // hack. calendar.js Hrrrrr!.
                if (node.id == 'from_mm')
                    node.id = 'from'+index+'_mm';
                else
                    if (node.id == 'from_dd')
                        node.id = 'from'+index+'_dd';
                    else
                        if (node.id == 'to_mm')
                            node.id = 'to'+index+'_mm';
                            else
                                if (node.id == 'to_dd')
                                    node.id = 'to'+index+'_dd';
                                    else
                                        node.id = node.id + index;
                node.name = node.id;
            }
        })
}

function updateChilds(node, index) {
    updateNodes(node.select('table'), index);
    updateNodes(node.select('select'), index);
    updateNodes(node.select('input'), index);
    updateNodes(node.select('td'), index);
    updateNodes(node.select('a'), index);
    updateNodes(node.select('img'), index);
    updateNodes(node.select('div'), index);
}




var DutieItem = Class.create({
    TemplateId: 'dutie_template',    
    initialize: function(itemId, parentName, parentId, containerId) {
        this.ParentName = parentName;
        this.ParentId = parentId;
        this.ItemId = itemId;
        this.ContainerId = containerId;
        this.DutieText = '';
        this.createItem();
    },
    createItem: function() {
        var newItem = $(this.TemplateId).cloneNode(true);
        newItem.id = this.ItemId;
        $(this.ContainerId).appendChild(newItem);
        updateChilds(newItem, this.ItemId);
        this.updateFields();
        // update remove button
        var removeHrefTemplate = new Template("javascript:#{parentName}Factory.getItemById('#{parentId}').removeDutieById('#{dutieId}');");
        var data_ = {parentName: this.ParentName, parentId: this.ParentId, dutieId: this.ItemId};
        $('remove_dutie_button' + this.ItemId).href = removeHrefTemplate.evaluate(data_);
        $('remove_dutie_button' + this.ItemId).show();
    },
    updateFields: function() {
        $('dutie' + this.ItemId).setValue(this.DutieText);
    },
    updateProperties: function() {
        this.DutieText = $('dutie' + this.ItemId).getValue();  
    },
    show: function() {
        $(this.ItemId).show();
    },
    removeItem: function() {
        $(this.ItemId).remove();
    }
});

var AboutItem = Class.create({
    ItemName: '',
    ItemId: '',
    ContainerId: '',
    TemplateId: '',
    Position: '',
    Company: '',
    FromDate: new Date(),
    ToDate: new Date(),
    ToPresent: false,
    Duties: Array(),

    initialize: function(itemName, itemId, containerId, templateId) {
        this.ItemName = itemName;
        this.ItemId = itemId;
        this.ContainerId = containerId;
        this.TemplateId = templateId;
        this.Position = '';
        this.Company = '';
        this.FromDate = new Date();
        this.ToDate = new Date();
        this.ToPresent = false;
        this.createItem();
        this.updateFields();
        this.Duties = new Array();
        this.MaxIndex = 0;
        //console.log("AboutItem create: ItemName=%s, ItemId=%s, ContainerId=%s, TemplateId=%s, Object=%o)", this.ItemName, this.ItemId, this.ContainerId, this.TemplateId, this);
    },
    addDutie: function(dutieText) {
        var newDutie = new DutieItem(this.ItemId + this.MaxIndex, this.ItemName, this.ItemId, 'dutie_container_'+this.ItemId);
        newDutie.DutieText = dutieText;
        newDutie.updateFields();
        newDutie.show();
        this.Duties.push(newDutie);
        this.MaxIndex++;
        //console.log("addDutie: dutieText=%s, DutieItem=%o", newDutie.DutieText, newDutie);
    },
    removeDutie: function(itemIndex) {
        this.Duties[itemIndex].removeItem();
        var new_items = Array();
        for (i = 0; i < this.Duties.size(); i++) {
            if (i != itemIndex)
                new_items.push(this.Duties[i]);
        }
        this.Duties = new_items;
    },
    getDutieIndexById: function(id) {
        //console.log("getDutieIndex: Duties=%o", this.Duties);
        for (i in this.Duties) {
            if (this.Duties[i].ItemId == id) {
                return i;                
            }
        }
        return -1;
    },
    getDutieById: function(id) {
        var index = this.getDutieIndexById(id);
        if (index != -1)
            return this.Duties[index];
        else
            return null;    
    },
    removeDutieById: function(id) {
        //console.log("removeDutieById: id=%s", id);
        var index = this.getDutieIndexById(id);
        if (index != -1) {
            this.removeDutie(index);
        }
    },    
    updateFields: function() {
        // TODO: update html
        $('position_' + this.ItemId).setValue(this.Position);
        $('company_' + this.ItemId).setValue(this.Company);
        $('from_' + this.ItemId + '_mm').setValue(this.FromDate.getMonth());
        $('from_' + this.ItemId + '_dd').setValue(this.FromDate.getDate());
        $('from_' + this.ItemId).setValue(this.FromDate.getFullYear());
        $('to_' + this.ItemId + '_mm').setValue(this.ToDate.getMonth());
        $('to_' + this.ItemId + '_dd').setValue(this.ToDate.getDate());
        $('to_' + this.ItemId).setValue(this.ToDate.getFullYear());
        if (this.ToPresent) {
            $('present_' + this.ItemId).checked = true;
        }
    },
    updateProperties: function() {
        this.Position = $('position_' + this.ItemId).getValue();
        this.Company = $('company_' + this.ItemId).getValue();
        this.FromDate.setFullYear($('from_' + this.ItemId).getValue(), $('from_' + this.ItemId + '_mm').getValue(), $('from_' + this.ItemId + '_dd').getValue());
        this.ToDate.setFullYear($('to_' + this.ItemId).getValue(), $('to_' + this.ItemId + '_mm').getValue(), $('to_' + this.ItemId + '_dd').getValue());
        this.ToPresent = $('present_' + this.ItemId).checked;
    },
    createItem: function() {
        var newItem = $(this.TemplateId).cloneNode(true);
        newItem.id = this.ItemId;
        $(this.ContainerId).appendChild(newItem);
        // update id of child items
        updateChilds(newItem, '_' + this.ItemId);
        // update calendar buttons
        $('date_picker_from_' + this.ItemId).writeAttribute('href', "javascript:displayDatePicker('from_"+this.ItemId+"');");
        $('date_picker_to_' + this.ItemId).writeAttribute('href', "javascript:displayDatePicker('to_"+this.ItemId+"');");
        // update remove button
        //$('remove_button_' + this.ItemId).href = "javascript:remove_"+this.ItemName+"_by_id('"+this.ItemId+"')";
        $('remove_button_' + this.ItemId).href = "javascript:"+this.ItemName+"Factory.removeById('"+this.ItemId+"')";
        $('remove_button_' + this.ItemId).show();
        // update add dutie button
        $('add_dutie_button_' + this.ItemId).href = "javascript:"+this.ItemName+"Factory.getItemById('"+this.ItemId+"').addDutie();";
    },
    show: function() {
        $(this.ItemId).show();
    },
    clearFields: function() {        
        this.Position = '';
        this.Company = '';
//        this.FromDate.setFullYear('');
//        this.ToDate.setFullYear('');
        this.updateFields();
    },
    removeItem: function() {
        $(this.ItemId).remove();
    }
});

var AboutItemFactory = Class.create({
    ItemName: '',
    MaxIndex: 0,    
    initialize: function(itemName) {
       this.ItemName = itemName;
       this.Items = new Array();
       this.MaxIndex = 0;
    },
    add: function(position, company, fromDate, toDate, toPresent) {
        var newItem = new AboutItem(this.ItemName, this.ItemName+'_'+this.MaxIndex, this.ItemName+'_container', this.ItemName+'_table');
        if (position)
            newItem.Position = position;
        if (company)
            newItem.Company = company;
        if (fromDate)
            newItem.FromDate = fromDate;
        if (toDate)
            newItem.ToDate = toDate;
        newItem.ToPresent = toPresent;
        newItem.updateFields();
        newItem.show()
        if (!position && !fromDate && !toDate && !toPresent) {
            newItem.addDutie('');
        }
        this.Items.push(newItem);
        this.MaxIndex++;
        //console.log("Factory Name=%s, Items=%o", this.ItemName, this.Items);
    },
    remove: function(itemIndex) {
        this.Items[itemIndex].removeItem();        
        var new_items = Array();
        for (i = 0; i < this.Items.size(); i++) {
            if (i != itemIndex)
                new_items.push(this.Items[i]);
        }
        this.Items = new_items;
    },
    getItemIndexById: function(id) {
        for (i in this.Items.toArray()) {
            if (this.Items[i].ItemId == id) {
                return i;
            }
        }
        return -1;
    },
    getItemById: function(id) {
        var index = this.getItemIndexById(id);
        if (index != -1)
            return this.Items[index];
        else
            return null;    
    },
    removeById: function(id) {
        var index = this.getItemIndexById(id);
        if (index != -1) {
            this.remove(index);
        }
    },
    show: function() {
        this.Items.each(function(item) {
            item.show();
        });
    },
    clearFields: function() {
        this.Items.each(function(item) {
            item.clearFields();
        })
    },
    getJSON: function() {
        var data_ = new Array();
        var duties_ = new Array();
        for (i = 0; i < this.Items.size(); i++) {                            
                duties_.clear();
                for (j = 0; j < this.Items[i].Duties.size(); j++) {
                    this.Items[i].Duties[j].updateProperties();
                    duties_.push(this.Items[i].Duties[j].DutieText);
                }
                this.Items[i].updateProperties();
                data_.push(new Hash({
                    position: this.Items[i].Position,
                    company: this.Items[i].Company,
                    from_yy: this.Items[i].FromDate.getFullYear(),
                    from_mm: this.Items[i].FromDate.getMonth(),
                    from_dd: this.Items[i].FromDate.getDate(),
                    to_yy: this.Items[i].ToDate.getFullYear(),
                    to_mm: this.Items[i].ToDate.getMonth(),
                    to_dd: this.Items[i].ToDate.getDate(),
                    present: this.Items[i].ToPresent,
                    duties: duties_
                }));
        }
        return Object.toJSON(data_);
    },
    setData: function(data) {
        // TODO
        //console.log('setData: data=%o', data);
        this.Items.clear();
        for(i = 0; i < data.size(); i++) {
            var item = data[i];
            from_date = new Date();
            to_date = new Date();
            from_date.setFullYear(item.from_yy, item.from_mm, item.from_dd);
            to_date.setFullYear(item.to_yy, item.to_mm, item.to_dd);
            this.add(item.position, item.company, from_date, to_date, item.present != '0');
            try {
            for (j = 0; j < item.duties.size(); j++) {
                this.Items.last().addDutie(item.duties[j]);
            }
            }
            catch(err) {
//                console.log("addDutie err: %s", err)
            }
        };
    }
});

var employmentFactory = new AboutItemFactory("employment");
var educationFactory = new AboutItemFactory("education");
var volunteerFactory = new AboutItemFactory("volunteer");
var serviceFactory = new AboutItemFactory("service");
var activitieFactory = new AboutItemFactory("activitie");


function BlockPage() {
    try {
        $('overlay').setStyle({display: 'block', top:0, left:0, width:'100%', height:'100%'});
    }
    catch (err) {

    }
}

function UnblockPage() {
    try {
        $('overlay').setStyle({display: 'none'});
    }
    catch (err) {

    }
}

function getAboutAjaxJSON() {
    getAboutAJ();    
}

function getAboutPreviewAjaxJSON(userId) {
    getAboutPreviewAJ(userId);
}

function setAboutAjaxJSON() {        
    setAboutAJ();       
}

function setAboutAJ() {
    new Ajax.Request('about.ajax.php', {
        method: 'post',
        parameters: {
            command: 'set_about_v2',
            user_bio: $('user_bio').getValue(),
            employment: employmentFactory.getJSON(),
            education: educationFactory.getJSON(),
            volunteer: volunteerFactory.getJSON(),
            service : serviceFactory.getJSON(),
            activitie: activitieFactory.getJSON()
        },
        onSuccess: function(transport) {
            var user_url = transport.responseText.evalJSON(true);
            window.location = 'http://www.webguild.org/user/'+user_url+'?about';
        }
    })
}

function getAboutAJ() {
    new Ajax.Request('about.ajax.php', {
        method: 'post',
        parameters: {
            command: 'get_about_v2'
        },
        requestHeaders: {
            Accept: 'application/json'
        },
        onSuccess: function(transport) {
            var about = transport.responseText.evalJSON(true);
            if (about) {
                //$('user_bio').setValue(about.user_bio);
                $('user_bio').update(about.user_bio);
                //console.log('bio length = %d', $('user_bio').getValue().length);
                setTextareaMaxLength('user_bio', 1300, 'bio_char_remain');
                employmentFactory.setData(about.employment);
                educationFactory.setData(about.education);
                volunteerFactory.setData(about.volunteer);
                serviceFactory.setData(about.service);
                activitieFactory.setData(about.activitie);
            }
        }
    });
}

function getChild(parentNode, childId) {
    return parentNode.select('[id="'+childId+'"]').first();
}

function showAboutHeader(headerText) {
    var header = $('about_header_template').cloneNode(true);    
    var header_text = getChild(header, "about_header_text");
    header_text.innerHTML = headerText;
    $('about_container').appendChild(header);
    header.show();
    header.id = "";
}
function showAboutItems(items) {
    var m_names = new Array("January", "February", "March",
                            "April", "May", "June", "July", "August", "September",
                            "October", "November", "December");
    try{
    //var date_ = new Date();
    //console.log("Items=%o", items);
    for (i = 0; i < items.size(); i++) {        
        var item = $('about_item_template').cloneNode(true);        
        getChild(item, "position").innerHTML = items[i].position;
        getChild(item, "company").innerHTML = items[i].company;        
        //date_.setFullYear(items[i].from_yy, items[i].from_mm, items[i].from_dd);
        getChild(item, "from_date").innerHTML = m_names[items[i].from_mm-1] + ' ' + items[i].from_yy;
        getChild(item, "to_date").innerHTML = m_names[items[i].to_mm-1] + ' ' + items[i].to_yy;
        if (items[i].present == "1") {
            getChild(item, "present").show();
            getChild(item, "to_date_container").hide();
        }
        else {
            getChild(item, "present").hide();
            getChild(item, "to_date_container").show();
        }
        $('about_container').appendChild(item);
        var dutie_container = getChild(item, "dutie_container");
        var showed_dutie_count = 0;
        for (j = 0; j < items[i].duties.size(); j++) {
            if (items[i].duties[j] != '') {
                var dutie = $('dutie_template').cloneNode(true);
                getChild(dutie, "dutie").innerHTML = items[i].duties[j];
                dutie.id = "";
                dutie_container.appendChild(dutie);
                dutie.show();
                showed_dutie_count++;
            }
        }
        if (showed_dutie_count == 0) {
            dutie_container.hide();
        }
        if (i == (items.size()-1)) {
            //getChild(item, "item_divider").hide();
            item.setStyle({borderBottom:'none'});
        }
        item.show();
        item.id = "";
    }
    
    }
    catch(err) {
        //console.log("catch: %s", err);
    }
}

function getAboutPreviewAJ(userId) {
    new Ajax.Request('about.ajax.php',  {
        method: 'post',
        parameters: {
            command: 'get_about_by_id_v2',
            user_id: userId
        },
        requestHeaders: {
            Accept: 'application/json'
        },
        onSuccess: function(transport) {
            var about = transport.responseText.evalJSON(true);
            if (about) {
                $('user_bio').innerHTML = about.user_bio;
                if (about.user_bio.length == 0) {
                        $('user_bio_container').hide();
                }
                if (about.employment.size() != 0)
                    showAboutHeader('Experience');
                showAboutItems(about.employment);
                if (about.education.size() != 0)
                    showAboutHeader('Education');
                showAboutItems(about.education);
                
                if (about.volunteer.size() != 0)
                    showAboutHeader('Volunteer');
                showAboutItems(about.volunteer)
                if (about.service.size() != 0)
                    showAboutHeader('Service');
                showAboutItems(about.service);
                if (about.activitie.size() != 0)
                    showAboutHeader('Activities');
                showAboutItems(about.activitie);
            }   
        }        
    });
}

function clearAboutFields() {
    $('user_bio').setValue('');
    employmentFactory.clearFields();
    educationFactory.clearFields();
    volunteerFactory.clearFields();
    serviceFactory.clearFields();
    activitieFactory.clearFields();
}

function setTextareaMaxLength(textarea, max_count, remains_out){
    var cur_count = $(textarea).getValue().length;
    var return_value = true;
    //console.log('cur_count = %d, max_count = %d', cur_count, max_count);
    if (cur_count > max_count) {
        cur_count = max_count;
        $(textarea).value = $(textarea).value.substr(0, max_count);
    }
    if (remains_out) {
//        console.log('remains_out = %s', $(remains_out).innerHTML);
        $(remains_out).innerHTML = (max_count-cur_count).toString();
//        console.log('remains_out = %s', $(remains_out).innerHTML);
    }
    return return_value;
}

