// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function getSelectedValue(select_obj, parameter) {
    var sel_index = select_obj.options.selectedIndex;
    // pass the parameter if you want to get back the result like
    // id=25, where 25 is the value of the selected option. 
    // I am calling this function in :with attribute of 
    // remote_function helper. If you don't pass the parameter, then
    // the else part is executed and the value of the selected option alone
    // will be returned.
    if(parameter != undefined) {
        return parameter + "=" + select_obj.options[sel_index].value;
    }
    else {
        return select_obj.options[sel_index].value;
    }
}


function reset_feedback_form(prefix) {
    $(prefix + '_email').value = "";
    $(prefix + '_message').value = "";
    //$(prefix + '_photo').value = "";
}

function show_tab(tab_title) {
    switch(tab_title) {
        case 'traffic' : $('maintabs').tabber.tabShow(0);break;
        case 'directions' : $('maintabs').tabber.tabShow(1); break;
        case 'buses' : $('maintabs').tabber.tabShow(2); break;
    }
}

function toggle_cities() {
    el = $('other_cities');
    if(el.style.display == "none") {
        Effect.SlideDown('other_cities');
    }
    else {
        Effect.SlideUp('other_cities');
    }
}

// opens a new browser window and loads it with the given url
function myPopup(mylink, windowname){
    if (! window.focus)return true;
    var href;
    if (typeof(mylink) == 'string')
        href=mylink;
    else
        href=mylink.href;
    window.open(href, windowname, 'width=600,height=270,scrollbars=yes');
    return false;
}

// Method called in case of results found for area-code.
function goto_search_result(area) {
    // Scroll to search result
    $(area).scrollIntoView(false);
    // Highlight result
    _bgcolor = $(area).getStyle('background-color');
    $(area).style.backgroundColor = '#F7DE21';
    
    // Remove highlight
    setTimeout("$('" + area + "').style.backgroundColor = '" + _bgcolor + "';", 10000);
}

// Method called in case of no results for area-code.
function no_search_result(textbox){
    $(textbox).style.backgroundColor = '#FF6633';
    setTimeout("$('" + textbox + "').style.backgroundColor = 'white'", 5000);
}

function send_message(button, id) {
    var msg = $("msg_" + id).value;
    if( ($("from_"+id).value.length > 0) && (msg.length > 0) ){
        button.value="Sending....";
        button.disabled = true;
        button.form.onsubmit();
        return;
    }
    alert('Please provide valid input');
}

function reset_form(form_obj) {
    form_obj.reset();
}

function reset_preferences_form() {
    form_obj = $('preferences_form');
    if(form_obj != null) {
        form_obj.reset();
    }
    $("mobile_no").value = "";
    $("name").value = "";
    Element.hide('preferences_form_container');
    window.scrollTo(0,0);
}

function check_availability() {
    mobileno = $('mobile_no').value;
    name = $('name').value;
    if(mobileno == "" || name == "") {
        alert('Please enter the mobile number and name');
        return;
    }
    new Ajax.Request('/carpool/check_availability?mobile_no='+mobileno+'&name='+name, {method: 'get', asynchronous: true, evalScripts: true, 
        onLoading: function() { Element.show('loading_indicator');},
        onComplete: function() { Element.hide('loading_indicator');} });
}

/* The following two functions belongs to the 
Carpool Join functionality */

function reset_join_form() {
    $('name').value="";
    $('mobile_no').value="";
    $('begin_button').disabled=false;
    $('name').disabled=false;
    $('mobile_no').disabled=false;
    $('preferences_form_container').hide();
    $('name').value = "";
    $('mobile_no').value =  "";
}

function disable_join_form() {
    $('name').disabled=true;
    $('mobile_no').disabled=true;
    $('begin_button').disabled=true;
}

function addStyleClass(div_id, style) {
    $(div_id).addClassName(style);
}

function removeStyleClass(div_id, style) {
    $(div_id).removeClassName(style);
}

function add_options(src_list_id, dest_list_id)
{
    src_options = $(src_list_id).options;
    dest_list = $(dest_list_id).options;
    deselect($(dest_list));
    for (var i = 0; i < src_options.length; i++)
        {
            if (src_options[i].selected && !isPresent(src_options[i], dest_list))
                {
                    option_element = Builder.node("option", { value : src_options[i].value , selected : true }, src_options[i].text);
                    $(dest_list_id).appendChild(option_element);
                }
            }
            
            deselect($(src_list_id).options);
            //selectAll(dest_list)
        }
        
        function selectAll(options) {
            for(var i=0;i<options.length;i++){
                options[i].selected = true;
            }
        }
        
        function isPresent(option, list)
        {
            for (var i=0;i<list.length;i++)
                {
                    if (list[i].value == option.value)
                        {
                            return true;
                        }
                    }
                    return false;
                }
                
                function deselect(options_list)
                {
                    for (var i=0;i<options_list.length;i++)
                        {
                            options_list[i].selected = false;
                        }
                    }
                    
                    function remove_selected(select_id) {
                        options = $(select_id).options;
                        for (var i=options.length-1; i>=0; i--)
                            {
                                if (options[i].selected)
                                    {
                                        Element.remove(options[i]);
                                    }
                                }
                            }
                            
                            function fnDispAlert()
                            {
                                if (show_alert) {
                                    new Ajax.Request('/main/disp_alert?page=' + pageNum, {asynchronous:true, evalScripts:true, method:'get'});
                                    pageNum++;
                                }
                            }
                            
                            function close_alert() {
                                $('alerts').innerHTML = "";
                                show_alert = false;
                            }
                            
                            function personalise() {
                                if(map.zoom <= 13) {
                                    alert("Please zoom in further to capture the exact location");
                                    return;
                                }
                                mc = map.getCenter();
                                var bounds = map.getExtent();
                                var auth_token;
                                new Ajax.Request('/main/get_authenticity_token', {method:'get',asynchronous: false, evalScripts:true, onComplete: function(res) { auth_token = eval("(" + res.responseText + ")").token; } })
                                pars = "zoom=" + map.zoom + "&lat=" + mc.lat + "&lon=" + mc.lon + "&top=" + bounds.top + "&left=" + bounds.left + "&right=" + bounds.right + "&bottom=" + bounds.bottom + "&authenticity_token=" + auth_token;
                                new Ajax.Request('/main/personalize', {asynchronous: true, evalScripts:true, parameters: pars, method:'post'})
                            }
                            
                            function populate_effective_and_earnings() {
                                scheduled_kms = $('revenue_collection_scheduled_kms').value;
                                cancelled_kms = $('revenue_collection_cancelled_kms').value;
                                effective_kms = scheduled_kms - cancelled_kms;
                                $('revenue_collection_effective_kms').value = effective_kms;
                                $('effective_kms').value = effective_kms;
                                revenue = $('revenue_collection_revenue').value;
                                earnings_per_km = revenue/effective_kms;
                                $('revenue_collection_earnings_per_km').value = earnings_per_km;
                                $('earnings_per_km').value = earnings_per_km;
                            }
                            
                            function populate_earnings_per_km() {
                                effective_kms = $('revenue_collection_effective_kms').value; 
                                revenue = $('revenue_collection_revenue').value;
                                earnings_per_km = revenue/effective_kms;
                                $('revenue_collection_earnings_per_km').value = earnings_per_km;
                            }
                            
                            function hideAckMessage() {
                                if($('http_msg')) {
                                    $('http_msg').innerHTML="";
                                    Element.hide('http_msg');
                                }
                            }
                            
                            function cancel_carpool_edit() {
                                $('pooler-prefs').innerHTML="";
                                $('cp-edit-form').show();
                                $('mobileno').value='Your Mobile Number';
                                ls.hideAll();
                                map.zoomTo(11);
                            }
                            
                            function toggle_details(id) {
                                Effect.toggle(id, 'slide');
                                visible = Element.getStyle(id, 'display');
                                if (visible == "block") {
                                    $('view-details-link-'+id).innerHTML = "&nbsp;(View Details)&nbsp;";
                                }
                                else {
                                    $('view-details-link-' +id).innerHTML = "&nbsp;(Hide Details)&nbsp;";
                                }
                            }
                            
                            var traffic_delays;
                            var pageNum = 0;
                            var show_alert = true;
                            
                            function filter_buses(route_no) {
                                Element.show("spinner");
                                var _keys = { lat : 'lat', lon : 'lon', label : 'desc', root : 'locations' };
                                if(route_no == undefined || route_no == null) {
                                    bus_no = $('routeno').options[$('routeno').options.selectedIndex].value;
                                }
                                else {
                                    bus_no = route_no;
                                }
                                var filtered_array = [];
                                var filtered_array_index = 0;
                                var buses = bus_tracking_info.locations;
                                extended_route = (bus_no.match(/[A-z]+$/) == null) ? false : true;
                                for(var i=0;i<buses.length;i++) {
                                    _hash = $H(buses[i]);
                                    if(  extended_route && _hash.get("desc").startsWith(bus_no) ) {
                                        filtered_array[filtered_array_index] = _hash;
                                        filtered_array_index = filtered_array_index + 1;
                                    }	
                                    else if( !extended_route && _hash.get("base_route") == bus_no ) {
                                        filtered_array[filtered_array_index] = _hash;
                                        filtered_array_index = filtered_array_index + 1;
                                    }
                                }
                                if(filtered_array.length==0) {
                                    alert("Sorry! We don't have location information for buses on this route.");
                                    Element.hide("spinner");
                                    $('routeno').options.selectedIndex=0;
                                    return;
                                }
                                var filtered_hash = new Hash();
                                filtered_hash.set('locations', filtered_array);
                                BtisMap.showLocations(filtered_hash.toJSON(), _keys, 'bmtctrack', false);
                                Element.hide("spinner");
                            }
                            
                            // -------------------------------------------------------------------
                            // moveOptionUp(select_object)
                            //  Move selected option in a select list up one
                            // -------------------------------------------------------------------
                            function moveOptionUp(obj) {
                                if (!hasOptions(obj)) { return; }
                                for (i=0; i<obj.options.length; i++) {
                                    if (obj.options[i].selected) {
                                        if (i != 0 && !obj.options[i-1].selected) {
                                            swapOptions(obj,i,i-1);
                                            obj.options[i-1].selected = true;
                                        }
                                    }
                                }
                            }
                            
                            // -------------------------------------------------------------------
                            // swapOptions(select_object,option1,option2)
                            //  Swap positions of two options in a select list
                            // -------------------------------------------------------------------
                            function swapOptions(obj,i,j) {
                                var o = obj.options;
                                var i_selected = o[i].selected;
                                var j_selected = o[j].selected;
                                var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
                                var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);
                                o[i] = temp2;
                                o[j] = temp;
                                o[i].selected = j_selected;
                                o[j].selected = i_selected;
                            }
                            
                            // -------------------------------------------------------------------
                            // hasOptions(obj)
                            //  Utility function to determine if a select object has an options array
                            // -------------------------------------------------------------------
                            function hasOptions(obj) {
                                if (obj!=null && obj.options!=null) { return true; }
                                return false;
                            }
                            
                            // -------------------------------------------------------------------
                            // moveOptionDown(select_object)
                            //  Move selected option in a select list down one
                            // -------------------------------------------------------------------
                            function moveOptionDown(obj) {
                                if (!hasOptions(obj)) { return; }
                                for (i=obj.options.length-1; i>=0; i--) {
                                    if (obj.options[i].selected) {
                                        if (i != (obj.options.length-1) && ! obj.options[i+1].selected) {
                                            swapOptions(obj,i,i+1);
                                            obj.options[i+1].selected = true;
                                        }
                                    }
                                }
                            }
                            
                            function showLoadingIndicator(text) {
                                if(text != null && text != undefined) {
                                    $('loading_indicator_text').innerHTML = text;
                                }
                                $('loading_indicator').show();
                            }
                            
                            function hideLoadingIndicator() {
                                if($('loading_indicator')) {
                                    Element.hide('loading_indicator');
                                    $('loading_indicator_text').innerHTML = 'Loading.. Please wait..';
                                }
                            }
                            
                            
