
// Global variables
var url_string = "";
var href = document.location.href;
href = (href.indexOf('&') > 0) ? (href.substring(0, href.indexOf('&'))) : href;
var tru_href = (href.indexOf('?') > 0) ? (href.substring(0, href.indexOf('?'))) : href;
var loading_img = new Image();
loading_img.src = '/images/loading.gif';

$(document).ready( function()
{
    var jcrop_api = new Object();
    
    window.setTimeout( function()
    {
        if($('#bus_picture_lg').length > 0)
        {
            jcrop_api = $.Jcrop('#bus_picture_lg', {
                setSelect: [10, 20, 30, 280],
                aspectRatio: 172/88
            });
        }
    }, 1000);
    
    /**
     * specsandrates.php logic
     *
     * If we are not logged in we must be signing up
     * require agree box to be checked before submitting the form
     * 
     * Check the box automatically for those that are already members and are editing their listing
     */
    
    if($('#spec').length > 0 && $('input[name="action"]').val() == 'update')
    {
        $('input[name="termsncond"]').attr('checked', 'checked'); 
    }
    
    $('#spec').submit( function()
    {
        if($('input[name="termsncond"]').attr('checked'))
        {
            return true;
        }
        else
        {
            alert('Please check "I have read and agree to terms" checkbox to continue.');
            $('input[name="termsncond"]').after(' <span class="form3" style="color: red;"> <u><b>Required</b></u> . . .</span>')
            return false;
        }
        
    });
    
    $('#commit_crop').live('click', function()
    {
        var x = jcrop_api.tellSelect().x
        var y = jcrop_api.tellSelect().y
        var w = jcrop_api.tellSelect().w
        var h = jcrop_api.tellSelect().h
        var img = $('#bus_picture_lg').attr('src');
        img = img.substr(img.lastIndexOf('/'), img.length);
        //img = img.substr(0, img.indexOf('?'));
        var grouping = $(this).closest('form').find('input[name="grouping"]').val();
        var query_string = 'action=crop_listing_image&img='+img+'&x='+x+'&y='+y+'&w='+w+'&h='+h+'&grouping='+grouping;
        
        $.ajax({
            type: "POST",
            url: tru_href,
            data: query_string,
            success: function(msg){
                //alert( "Data Saved: " + msg );
                $('#bus_picture').html(msg);
            }
        });
    });
    
    $('#edit :checkbox:first').live('click', function()
    {
        if($(this).attr('checked') === true)
        {
            $('#edit :checkbox').attr('checked', 'checked');
            $('#edit :checkbox:not(:first)').parent('td').css('background-color', '#FFF7BB');
            $('#edit :checkbox:not(:first)').parent('td').siblings().css('background-color', '#FFF7BB');
        }
        else
        {
            $('#edit :checkbox').attr('checked', '');
            $('#edit :checkbox:not(:first)').parent('td').css('background-color', '#FFFFFF');
            $('#edit :checkbox:not(:first)').parent('td').siblings().css('background-color', '#FFFFFF');
        }
    });
    
    $('#edit :checkbox:not(:first)').live('click', function()
    {
        if($(this).attr('checked') === true)
        {
            $(this).parent('td').css('background-color', '#FFF7BB');
            $(this).parent('td').siblings().css('background-color', '#FFF7BB');
        }
        else
        {
            $(this).parent('td').css('background-color', '#FFFFFF');
            $(this).parent('td').siblings().css('background-color', '#FFFFFF');
        }
    });
            
    $('a.edit_specsandrates').hover(
        function()
        {
            $(this).children('img').css('visibility', 'visible');
        },
        function()
        {
            $(this).children('img').css('visibility', 'hidden');
        }
    );
    
    $('a.dynamic_link').live('click', function(e)
    {
        var content = request_page($(this).attr('href'), true, e)
        $('#vendor_reviews').html(content);
        
        $(':input[name=vendor_response]').focus(function()
        {
            $(this).css('border', '2px solid orange');
        });
        
        $(':input[name=vendor_response]').blur(function()
        {
            $(this).css('border', '1px solid black');
        });
    
        $('form[name*="vendor_review"]').submit( function(e)
        {
            var vendor_response = $(this).find(':input[name="vendor_response"]').val();
            var page = $(this).attr('action') + '?';
            var url_string = ''
            
            $(this).find(':input').not(':submit').each( function()
            {
                url_string += '&' + $(this).attr('name') + '=' + escape($(this).val());
            });
            
            url_string = url_string.substring(1, url_string.length);
            
            var content = request_page(page + url_string, true, e);
            
            $(this).find('#fieldset_response').html(content);
            
            return false;
        });
        
        return false;
    });
    
    $('.edit_vendor_review').live('click', function()
    {
        var vendor_review_container = $(this).parents('tr:first').siblings('tr').eq(0).children('td');
        var vendor_review = $(vendor_review_container).html();
        
        var submit_button = document.createElement('input');
        submit_button.setAttribute('type', 'submit');
        submit_button.setAttribute('value', 'Submit');
        
        var table_row = document.createElement('tr');
        var table_cell = document.createElement('td');
        table_cell.setAttribute('colspan', '2');
        $(table_cell).html(submit_button);
        $(table_row).html(table_cell);
        
        var textarea_field = document.createElement('textarea');
        textarea_field.setAttribute('cols', '63');
        textarea_field.setAttribute('rows', '5');
        textarea_field.setAttribute('name', 'vendor_response');
        
        $(textarea_field).html(vendor_review);
        $(vendor_review_container).html('Max 255 Characters <br/>');
        $(vendor_review_container).append(textarea_field);
        $(this).parents('table').eq(1).append(table_row);
        $(this).parents('tr:first').remove();
        
        return false;
    });
    
    $('#fieldset_response textarea').live('keyup', function()
    {
        var field_value = $(this).val();
        
        if(field_value.length > 255)
        {
            $(this).val(field_value.substring(0, 255));
        }
    });
    
    $('form[name="traffic_report"] :submit').unbind('click');
    $('form[name="traffic_report"]').submit( function()
    {
        var url_string_pieces = Array();
        var i = 0;
        $(this).find(':input').each( function()
        {
            var input_type = $(this).attr('type');
            var input_name = $(this).attr('name');
            var input_value = $(this).val();
            
            url_string_pieces[i] = (input_type == 'checkbox' && $(this).attr('checked') == false) ? (input_name + '=') : (input_name + '=' + input_value);
            i++;
        });
        
        var url_string = url_string_pieces.join('&');
        
        $.ajax(
        {
            url: $(this).attr('action'),
            type: "POST",
            data: url_string,
            dataType: "html",
            beforeSend: function()
            {
                $('#traffic_report').html('Loading . . .');
            },
            success: function(response)
            {
                $('#traffic_report').html(response);
                
                $('.click_details tr').each( function() {
                    $(this).children('td:first').hover(
                        function() {
                            $(this).children('span').show();
                        },
                        
                        function() {
                            $(this).children('span').hide();
                        }
                    );
                });
            }
        });
        
        return false;
    });
    
    $('.clear_choice').each( function() {
        $(this).click( function() {
            $radio_name = $(this).attr('radio_name');
            $('form[name=update_tier] input[name='+$radio_name+']:radio').each( function() {
                $(this).attr('checked', false);
            });
            return false;
        });
    });
    
    $(':submit').live('click', function()
    {
        var form_name = $(this).closest('form').attr('name');
        
        if(typeof($(this).closest('form:not([name*=vendor_review])')) != 'undefined' && form_name.indexOf('review') < 1 && typeof($(this).attr('confirm_msg')) != 'undefined')
        {
            if($(this).attr('value') == "Submit New Listing Request(s)") {
                var answer = confirm($(this).attr('confirm_msg') + '\n\nPlease confirm that you would like to adjust your rank.');
            }
            else {
                var answer = confirm('Are you sure you would like to perform this action?');
            }
            
            if(answer) {
                $(this).attr('disabled', 'disabled');
                $(this).closest('form').submit();
                return true;
            }
            else {
                return false;
            }
        }
    });
    
    $('select#bus_types').change( function()
    {
        var bus_type = $(this).val();
        var qty = $(this).closest('tr').find('input[name*="qty"]').val();
        if(bus_type == 'B' || bus_type == '0')
        {
            $(this).closest('tr').find('input[name*="qty"]').attr('disabled', 'disabled');
            $(this).closest('tr').find('input[name*="qty"]').val('--');
            $(this).closest('tr').find('input[name*="qty"]').css('background-color', '#EEEEEE');
        }
        else if(qty != '' && qty != '--')
        {
            $(this).closest('tr').find('input[name*="qty"]').attr('disabled', '');
            $(this).closest('tr').find('input[name*="qty"]').css('background-color', '#FFFFFF');
        }
        else
        {
            $(this).closest('tr').find('input[name*="qty"]').attr('disabled', '');
            $(this).closest('tr').find('input[name*="qty"]').val('');
            $(this).closest('tr').find('input[name*="qty"]').css('background-color', '#FFFFFF');
        }
    });
    
    $('a.delete_image').live('click', function(e)
    {
        if(confirm("Are you sure you want to permanently remove this image?"))
        {
            var content = request_page($(this).attr('href'), true, e);
            $(this).siblings('div.jcrop-holder').remove();
            $(this).siblings('img').attr('src', '/images/bus_pictures/no_photo.png');
            $(this).remove();
        }
        return false;
    });
    
    //-------------------------------------------------------------------------
    //  Text counter
    //-------------------------------------------------------------------------
    $('textarea.countText255').bind('keydown, keyup', function()
    {
        var liveText = $(this).val();
        
        if(liveText.length > 255)
        {
            $(this).val(liveText.substring(0, 255));
            liveText = $(this).val();
        }
        
        $('.charsLeft').html(255 - liveText.length);
    });
    
});

//--------------------------------------------------------------------------
//  Request a page from the server
//--------------------------------------------------------------------------
function request_page(page_url, return_content, e) {
    var content = '';
    var url_string = '';
    
    if((page_url.split('?').length) > 0)
    {
        url_string += page_url.substring(page_url.indexOf('?', page_url) + 1, page_url.length);
    }
    
    if((page_url.split('?').length) != 0)
    {
        page_url = page_url.substring(0, page_url.indexOf('?', page_url));
    }
    
    $.ajax(
    {
        type: "POST",
        async: false,
        url: page_url,
        dataType: "html",
        data: url_string,
        beforeSend: function()
        {
            /*if(return_content === false)
            {
                $('.ajx_page').fadeTo(200,.05);
            }*/
            create_loading(e); // located in main.js
        },
        success: function(html)
        {
            content = html;
            
            /*$(xml).find("response").each(function()
            {
                content = jQuery.trim($(this).children("content").text());
                if(return_content === false)
                {
                    window.setTimeout( function()
                    {
                        // Insert retrieved content
                        $('.ajx_page').html(content).fadeTo(200,1);
                    }, 200);
                }
            });*/
            
            return false;
        },
        complete: function (XMLHttpRequest, textStatus)
        {
            destroy_loading();
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
            /*window.setTimeout( function()
            {
                $('.ajx_page').html('There was an error with you request.  Please contact customer service. '+XMLHttpRequest.responseText+'Status Text: <b>' + XMLHttpRequest.statusText + '</b> Error Thrown: <b>' + errorThrown + '</b>').fadeTo(200,1);
            }, 200);
        */}
    });
    
    return (return_content === true) ? (content) : (false);
}

//*************************************************************************
//  Remove the loading layover
//*************************************************************************
function destroy_loading()
{
    remove_element('#loading_container');
    remove_element('#loading_image');
}

//*************************************************************************
//  Create a loading layover
//*************************************************************************
function create_loading(e)
{
    if(typeof(e.pageY) == 'undefined')
    {
        var loading_height = $('body').height();
        var loading_width = $('body').width();
        var scroll_pos = (window.pageYOffset) ? (window.pageYOffset) : (document.body.scrollTop);
        var loading_img_top = ($(window).height() / 2) + (loading_img.height / 2) + (scroll_pos);
        var loading_img_left = (loading_width / 2) - (loading_img.height / 2);
    }
    else
    {
        var loading_img_top = e.pageY + 20;
        var loading_img_left = e.pageX + 20;
    }

    $('body').append('<img id="loading_image" src="' + loading_img.src + '" />');
    $('#loading_image').css({
        display:'none',
        position:'absolute',
        top:loading_img_top,
        left:loading_img_left,
        zIndex:'1002'
    }).show();
}

//*************************************************************************
//  Remove an element from the DOM
//*************************************************************************
function remove_element(el)
{
    $(el).fadeOut(500);
    window.setTimeout( function() {
        $(el).remove();
    }, 1500);
}
