/*
    Document   : open-geodata.js
    Created on : 29 Απρ 2010, 2:16:06 μμ
    Author     : paris
    Description:
        JS functions to support required web-page functionality.
*/


/*
 *      Controller - Actions
 */

var domainURL="http://www.geodata.gov.gr";


// If all data is to be shown we have to remove the alldata from the search field.
function init_search_field()
{
    if (jQuery("#sobi2Search").val() == "alldata")
    {
        jQuery("#sobi2Search").val("");
    }
}

// The user has selected to group data by "foreis"
function list_data_owners()
{
    ;
}

// The user wants to see the most popular keywords along with the number of occurrence.
function list_popular_keywords()
{
    ;
}

// When user hits contact button, we reveal the contcat form (sobi2 - Detailed View).
function show_contact_form()
{
    if (jQuery("#c_form").css('display') == "none")
    {
        jQuery("#c_fieldset").css('border-color', '#CCE');
        jQuery("#c_form").show('toggle');
    }
    else
    {
        jQuery("#c_form").hide('toggle');
        jQuery("#c_fieldset").css('border-color', '#F7F7F7');
    }
}

// After ajax request for ownerhips is successful, we have to plant the returned data in to the page.
function show_data_owners(ownership)
{
    ;
}

// After ajax request for "most popular keywords" is successful, we have to plant the returned data in to the page.
function show_pupular_keywords(keyword)
{

}

// When the user clicks, show all data.
function showAllData()
{
    //window.location = "/open-geodata/index.php?option=com_sobi2&sobi2Task=search&sobi2Search=alldata";
    window.location = "index.php?option=com_sobi2&sobi2Task=search&sobi2Search=alldata";
}

// This function is dispatched when the user clicks on the send message button.
function save_message()
{
    // show ajax loader
    jQuery("#c_send_button").addClass("sending");
    
    // Attention is required. 
    // String may contain illegal characters and may cause problem in database query execution.
    
    var msg    = jQuery("textarea#c_textarea").val();
    var sender = jQuery("input#c_sender").val(); 
    var about  = jQuery("div#sobi2Details_title")[0].innerHTML ;

    send_message(sender, about, msg);

    return;
}

// The form has to close after a while, since the message was successfuly sent.
function clearAndCloseMessageForm(timeout)
{
    setTimeout(
      'jQuery("#c_send_button").removeClass("sent"); '+
      'jQuery("textarea#c_textarea").val(""); '+
      'jQuery("input#c_sender").val(""); '+
      'show_contact_form()', 
    timeout);
}

function showXmlUploader()
{
    if (jQuery("#importXML").attr("checked"))
        jQuery("#xmlFile").show();
    else
        jQuery("#xmlFile").hide();
}

function hideXmlUploader()
{
    jQuery("#xmlFile").hide();
}


function showXmlUploader()
{
    if (jQuery("#importXML").attr("checked"))
    {
        jQuery("#subdir").show();
        jQuery("input[name='parseXML']").show();
    }
    else
    {
        jQuery("#subdir").hide();
        jQuery("input[name='parseXML']").hide();
    }
}



/*
 *      Ajax
 */
// Get the "foreis" along with the number of dataset per each.
function fetch_data_group_by()
{

}

// Get the most popular keywords. A parameter of how many keywords we want, is passed.
function fetch_keywords(keywords_num_threshold)
{
    
}

// Send user message to server.
function send_message(sender, about, msg)
{
    var qs = window.location.search;
    var pos = qs.search("sobi2Id=");

    if (pos < 0) {
        console.error ("Cannot find 'sobi2Id' GET param!");
        return;
    }

    var item_id = parseInt(qs.substring(pos +("sobi2Id=").length));
    if (isNaN(item_id)) {
        var errmsg = "Cannot parse 'sobi2Id' GET param into a valid integer!";
        if (typeof(console) == 'object')
            console.error(errmsg);
        else 
            alert(errmsg);
        return;
    }

    var post_url  = "components/com_sobi2/open-geodata/save_message.php";
    var post_data = {
        "message":       msg.toString(), 
        "contact_to":    sender.toString(),
        "about":         about.toString(),
        "sobi2_item_id": item_id.toString() 
    };
    
    /*console.dir(post_data);*/ 

    jQuery.post(post_url, post_data, function(data) {
        setTimeout(
          'jQuery("#c_send_button").removeClass("sending");'+
          'jQuery("#c_send_button").addClass("sent");'+
          'clearAndCloseMessageForm(1000)', 1000);
    });

    return;
}


// Fetch JSON from XML parsing.
// Function called when in data entry mode, xml is provided as source.
function fetchJSONfromXML()
{
    jQuery.getJSON("components/com_sobi2/open-geodata/parseXML.php", {dataPath: jQuery("#subdir").val()}, function (data)
    {
        jQuery("#field_entry_name").val(data.name);
        jQuery("#field_description").val(data.description);
        jQuery("#field_availability_date").val(data.availability_date);
        jQuery("#field_last_update").val(data.last_update);
        jQuery("#field_update_freq").val("-");
        jQuery("#field_name").val(data.name);
        jQuery("#field_license").val(data.license);
        jQuery("#field_version").val(data.version);
        jQuery("#field_geo_extend").val(data.geo_extend);
        jQuery("#field_time_extend").val(data.time_extend);
        jQuery("#field_uid").val(data.uid);
        jQuery("#field_mapfish_link").val(data.permalink);
        jQuery("#field_metadata").val("/datasets/"+data.metadata_filepath);
        jQuery("#field_contact_point").val(data.contact_point);
        jQuery("#field_cp_communication").val(data.communication);
        jQuery("#sobi2MetaKey").val(data.meta_keywords);
        jQuery("#field_folder_path").val(jQuery("#subdir").val());

        // Checkout the provider.
        // Fetch existing providers.
        var cat = jQuery(".treeNode");
        var cat_num = cat.length;
        var provider_exists = false;
        var provider = "'"+trim(data.provider)+"'";

        for (var i=0; i<cat_num; i++)
        {
            cat[i] = "'" + trim(jQuery(cat[i]).html()) + "'";
            if (cat[i] == provider)
            {
                // Auto select provider when found.
                onSelectedCat('.',trim(data.provider),'16');
                addCategory();
                
                provider_exists = true;
                break;
            }
        }

        if (!provider_exists)
        {
            var td = jQuery("#sobi2FormCatsItroRow td");
            jQuery(td).empty();

            jQuery(td).attr("colspan", 1);
            jQuery("<div style='float: left;'>Ο φορέας <b>"+data.provider+"</b> δεν υπάρχει στην τρέχουσα λίστα. </div>").appendTo(jQuery(td));
            jQuery("<input style='margin-left: 5px;' type='button' onclick='addProvider(\""+data.provider+"\")' value='Προσθήκη'/>").appendTo(jQuery(td));
        }
        else
            ;//alert("provider exists");

    }
    );
}

// If provider in xml file does not exist in list, it has to be added.
function addProvider(name)
{
    jQuery.get("components/com_sobi2/open-geodata/addProvider.php", {provider_name: name}, function (id)
    {
        if (id != "error") {
            jQuery(
                '<div class="sigsiuTreeNode"> '+
                    '<img alt="" id="sobi2CatsForm_imgJoin'+id+'" style="border-style: none;" src="components/com_sobi2/images/join.gif">'+
                    '<a id="sobi2CatsForm_imgFolderUrl'+id+'" href="javascript:onSelectedCat(\'.\',\''+name+'\',\''+id+'\')">'+
                       '<img alt="" id="sobi2CatsForm_imgFolder'+id+'" style="border-style: none;" src="components/com_sobi2/images/folder.gif">'+
                    '</a>'+
                    '<a id="sobi2CatsForm_CatUrl'+id+'" class="treeNode" href="javascript:onSelectedCat(\'.\',\''+name+'\',\''+id+'\')">ΟΚΧΕ</a>'+
                '</div>'
            ).appendTo('#sobi2CatsForm');
        } else {
            alert(id);
        }
    });
}

function on_uuid_ready(res, status_txt) 
{
    if (res.uuid == undefined)
        console.info("on_uuid_ready: undefined property 'uuid'");
    else 
        jQuery("#field_uid").val(res.uuid.toString());

    console.log ("on_uuid_ready: received a new UUID ("+status_txt+")"); 
    
    return;
}

function form_fill_field_uid() 
{
    var curr_val = jQuery("#field_uid").val();

    var task_qs = window.location.search.toString().match(/Task=(\w*)/);

    var task = (task_qs != null)? (task_qs[1]) : ("");

    /* check if we must generate a new UUID */

    if (curr_val.length == 0 && task == "addNew") {
        /* request a new UUID to fill input with  */    
        jQuery.getJSON("/datasets/utils/uuid_generator.php?", on_uuid_ready);
        console.log ("form_fill_field_uid: requested a new UUID");
    } else {
        /* the input is allready filled */
        console.log ("form_fill_field_uid: allready exists: uuid="+curr_val);
    }

    return true;        
}


function on_data_subdir_created(res, status_txt)
{
    console.log ("on_data_subdir_created: i am here!");

    if (status_txt != 'success' || res.status_text == 'failure') {
        console.info ( "on_data_subdir_created: failed!" );
        return false;
    }
    
    if (confirm("Να καταχωρηθουν τα δεδομενα ??")) {
        jQuery("#sobi2EditForm")[0].submit();       
    }

    return false;       
}

function form_create_data_subdirs() 
{
    var uuid = jQuery("#field_uid").val();

    console.log ( "form_create_data_subdirs: uuid="+uuid);
    
    /* We return false so that form is not submitted. 
     * The form will actually be submitted only when our 
     * ajax request (getJSON) completes 
     */

    if (uuid == undefined)
        return false;
    else {
        jQuery.getJSON("/datasets/utils/create_subdir.php?&uuid="+uuid, on_data_subdir_created);
        return false;
    }
}


// Ajax loader manipulation.
function apply_shade()
{
    
}

function remove_shade()
{
    
}

/*
 *     Utility functions
 */

function trim (str) {
    var str = str.replace(/^\s+/, ''),
        ws = /\s/,
        i = str.length;
    while (ws.test(str.charAt(--i)));
    return str.slice(0, i + 1);
}


function query_string_replace(url, key, val){
    var re = new RegExp("[&]?(\\w*)=([\\w\\x2D\\x25]*)","g"); /* g: globally*/
    var qs = ''; 
    var j  = url.lastIndexOf("?");
    var subj = url.substring(1 + j);    
    re.lastIndex = 0;
    while( (m = re.exec(subj)) != null ){
        if( m[1] == key ){ /* found (key,value) pair */
            // nop 
        } else { 
            qs +=  m[0] ;
        }
    }
    qs += "&"+key+"="+val;
    return url.substring(0,j) + "?" + qs ;
}

