function isArray(testObject)
{
    return testObject && !(testObject.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject.length === 'number';
}

function dump(arr, level)
{
    var dumped_text = '';
    var level_padding = '';

    if (!level) level = 0;

    for (var j = 0; j < level + 1; j++) level_padding += '    ';

    if (typeof(arr) == 'object') 
    {
        for (var item in arr) 
        {
            var value = arr[item];

            if (typeof(value) == 'object') 
            {
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += dump(value, level + 1);
            } 
            else
            {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    }
    else
    {
        dumped_text = '===>' + arr + '<===(' + typeof(arr) + ')';
    }

    return dumped_text;
}

$.fn.QSpopulate = function(page, text) 
{
    this.each(function() {
        var elem = $(this);

        elem.attr('disabled', 'disabled').html('<option selected="selected" value="">Populating... Please Wait...</option>');

        $.getJSON(page, null, function(data)
        {
            if (elem.attr('id') == 'QSregion' && data.result == '')
            {
                elem.html('<option selected="selected" value="">No Regions... Select A City</option>');
                $('#QScity').removeAttr('disabled').css('color', '#000');
            }
            else
            {
                if($.browser.msie){ 
                    if (text == 'Select A Country')
                    {
                        elem.get(0).outerHTML = '<select id="' + elem.attr('id') + '" class="' + elem.attr('class') + '">' + data.result + '</select>';
                    }
                    else
                    {
                        elem.get(0).outerHTML = '<select id="' + elem.attr('id') + '" class="' + elem.attr('class') + '"><option value="">' + text + '</option>' + data.result + '</select>';
                    }
                }
                else
                {
                    if (text == 'Select A Country')
                    {
                        elem.html(data.result);
                    }
                    else
                    {
                        elem.html('<option value="">' + text + '</option>' + data.result);
                    }   
                }

                elem.removeAttr('disabled');
            }
        });
    });

    return this;
};

$.fn.populate = function(page, text) 
{
    this.each(function() {
        var elem = $(this);

        elem.attr('disabled', 'disabled').html('<option selected="selected" value="">Populating... Please Wait...</option>');

        $.getJSON(page, null, function(data)
        {
            if (elem.attr('id') == 'region' && data.result == '')
            {
                elem.html('<option selected="selected" value="">No Regions... Enter A City</option>');
                $('#city').removeAttr('disabled').css('color', '#000');
            }
            else
            {
                if($.browser.msie){
                    if (text == 'Select A Country')
                    {
                        elem.get(0).outerHTML = '<select id="' + elem.attr('id') + '" class="' + elem.attr('class') + '">' + data.result + '</select>';
                    }
                    else
                    {
                        elem.get(0).outerHTML = '<select id="' + elem.attr('id') + '" class="' + elem.attr('class') + '"><option value="">' + text + '</option>' + data.result + '</select>';
                    } 
                }                             
                else
                {
                    if (text == 'Select A Country')
                    {
                        elem.html(data.result);
                    }
                    else
                    {
                        elem.html('<option value="">' + text + '</option>' + data.result);
                    }
                }

                elem.removeAttr('disabled');
            }
        });
    });

    return this;
};

$(document).ready(function() {
    var cache = {};

    // Favs mouseover
    $('.addfav').mouseover(function() {
        $(this).find('img').attr('src', $(this).find('img').attr('tag') + '-mouseover.png');
    }).mouseout(function() {
        $(this).find('img').attr('src', $(this).find('img').attr('tag') + '.png');
    });
    
    $('.profile-button').click(function(event) {
        var elem = $(this);
        
        if ($(this).attr('link') == 'chat')
        {
            if ($(this).attr('credits') >= 1)
            {
                $.get("/auto/start_chat/" + $(this).attr('reci'), function(data) {
                    $('body').prepend('<div style="position: absolute; top: 50px; left: 100px; width: 350px; height: 401px; border: 2px solid #95999C; z-index: 10;" chatid="' + data.split('-')[0] + '" class="chat-window" id="chatwindow-' + elem.attr('recu') + '" url="identifier=' + data + '&sender=' + elem.attr('myu') + '&senderi=' + elem.attr('myi') + '&senderp=' + elem.attr('myp') + '&reciever=' + elem.attr('recu') + '&recieveri=' + elem.attr('reci') + '">' +
                        '    <div class="chat-title" style="cursor: move; background-color: #27619C; width: 100%; height: 25px; border-bottom: 2px solid #95999C;">' +
                        '        <span style="color: #ffffff; font-weight: bold; display: block; padding-top: 3px; padding-left: 5px;">Swurve Chat - ' + elem.attr('recu') + '</span>' +
                        '        <div class="chat-close" style="position: absolute; cursor: pointer; right: 0px; top: 0px; background-color: #24254F; height: 25px; width: 25px; border-left: 2px solid #95999C;">' +
                        '            <div style="color: #ffffff; font-weight: bold; margin-top: 3px; margin-left: 7px;">X</div>' +
                        '        </div>' +
                        '    </div>' +
                        '    <div id="chatcontainer-' + data.split('-')[0] + '"></div>');
                        /*
                        '    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="350" height="400" id="chat-<?= $chat; ?>" align="middle">' +
                        '        <param name="allowScriptAccess" value="sameDomain" />' +
                        '        <param name="allowFullScreen" value="false" />' +
                        '        <param name="movie" value="/assets/Deux.swf" />' +
                        '        <param name="quality" value="high" />' +
                        '        <param name="bgcolor" value="#ffffff" />' +
                        '        <param name="flashvars" value="sender=<?= Core::$user->username ?>&senderi=<?= Core::$user ?>&senderp=<?= Core::$user->password ?>&reciever=<?= $reciever->username; ?>&recieveri=<?= $reciever; ?>&identifier=<?= $chat . '-' . $chat->unique ?>" />' +
                        '        <embed src="/assets/Deux.swf" flashvars="sender=<?= Core::$user->username ?>&senderi=<?= Core::$user ?>&senderp=<?= Core::$user->password ?>&reciever=<?= $reciever->username; ?>&recieveri=<?= $reciever; ?>&identifier=<?= $chat . '-' . $chat->unique ?>" quality="high" bgcolor="#ffffff" width="350" height="400" name="chat-<?= $chat; ?>" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />' +
                        '    </object>' +
                        '</div>');*/
                        
                    var flashvars = {
                        sender: elem.attr('myu'),
                        senderi: elem.attr('myi'),
                        senderp: elem.attr('myp'),
                        reciever: elem.attr('recu'),
                        recieveri: elem.attr('reci'),
                        ignoreprompt: elem.attr('ignore'),
                        identifier: data
                    };
                    var params = {
                        wmode: 'opaque'
                    };
                    var attributes = {
                        id: "chat" + data.split('-')[0],
                        name: "chat" + data.split('-')[0]
                    };
                    
                    swfobject.embedSWF("/assets/Deux.swf?" + Math.random() * 9999999, "chatcontainer-" + data.split('-')[0], "350", "374", "9.0.0", "", flashvars, params, attributes);
                    
                    $('#chatwindow-' + elem.attr('recu')).focus();
                    
                    $('html,body').animate({scrollTop: $('#chatwindow-' + elem.attr('recu')).offset().top-400},500);
                });
            }
            else
            {
                if (confirm('You do not have enough credits to initiate a chat session.\n Would you like to go to the credit purchase page now?'))
                {
                    alert('open credit purchase page');
                }
            }
        }
        else
        {
            location.href = $(this).attr('link');
        }
    });

    //$('#QScountry').QSpopulate('/json/countries', 'Select A Country');

    $('#QScountry').live('change', function()
    {
        if ($(this).val() != '')
        {
            $('#QScity').attr('disabled', 'disabled').val('Enter A City').css('color', '#808080');
            $('#QSregion').populate('/json/regions/' + $(this).val().toLowerCase(), 'Select A Region');
        }
        else
        {
            $('#QSregion').attr('disabled', 'disabled').html('<option selected="selected" value="">Select A Region</option>');
            $('#QScity').attr('disabled', 'disabled').val('Enter A City').css('color', '#808080');
        }
    });

    $('#QSregion').live('change', function()
    {
        $('#city_id').val('');
        
        if ($(this).val() != '')
        {
            if ($(this).find('option').size() > 1)
            {
                $.getJSON('/json/count/' + $('#QScountry').val().toLowerCase() + '/' + $(this).val().toLowerCase(), null, function(data)
                {
                    if (data.result[0]['count'] == 0)
                    {
                        $('#QScity').attr('disabled', 'disabled').val('No Cities For This Region').css('color', '#808080');
                    }
                    else
                    {
                        $('#QScity').removeAttr('disabled').css('color', '#000').val('Enter A City');
                    }
                });
            }
        }
        else
        {
            $('#QScity').attr('disabled', 'disabled').val('Enter A City').css('color', '#808080');
        }
    });

    $("#QScity").autocomplete({
        source: function(request, response) {
            if (cache.term == request.term && cache.content) {
                response(cache.content);
            }
            if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
                var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                response($.grep(cache.content, function(value) {
                    return matcher.test(value.value)
                }));
            }

            $.ajax({
                url: '/json/cities/' + $('#QScountry').val().toLowerCase() + '/' + (($('#QSregion').val() == '') ? '00' : $('#QSregion').val()),
                dataType: "json",
                data: request,
                success: function(data) {
                    cache.term = request.term;
                    cache.content = data;
                    response(data);

                    $.each(cache.content, function(i, val) {
                        if ($(this).val().toLowerCase() == val.value.toLowerCase())
                        {
                            found = true;
                            $(this).val(val.value);
                            $('#city_id').val(val.id);
                        }
                    });
                }
            });
        },
        minLength: 2,
        select: function(event, ui) {
            $('#city_id').val(ui.item.id);
        }
    });

    $('#QScity').focus(function() {
        if ($(this).val() == 'Enter A City')
        {
            $(this).val('');
        }
    });

 /*   $("#QScity").blur( function() {
        var city = this;
        var found = false;

        $.each(cache.content, function(i, val) {
            if ($(city).val().toLowerCase() == val.value.toLowerCase())
            {
                found = true;
                $(city).val(val.value);
                $('#city_id').val(val.id);
            }
        });

        if (found == false)
        {
            $(city).val('');
        }
    });
*/
    $("#QScity").keypress(function (e) {   
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {   
            return false;   
        }
    });

    // Country / Region / City search code
    if (location.pathname != '/user/register' && location.pathname != '/edit/profile' && location.pathname.indexOf('/admin/manage/user/') < 0) {
        //$('#country').populate('/json/countries', 'Select A Country');
    }
    
    $('#country').live('change', function()
    {
        if ($(this).val() != '')
        {
            $('#city').attr('disabled', 'disabled').val('Enter A City').css('color', '#808080');
            $('#region').populate('/json/regions/' + $(this).val().toLowerCase(), 'Select A Region');
        }
        else
        {
            $('#region').attr('disabled', 'disabled').html('<option selected="selected" value="">Select A Region</option>');
            $('#city').attr('disabled', 'disabled').val('Enter A City').css('color', '#808080');
        }
    });

    $('#region').live('change', function()
    {
        $('#city_id').val('');

        if ($(this).val() != '')
        {
            if ($(this).find('option').size() > 1)
            {
                $.getJSON('/json/count/' + $('#country').val().toLowerCase() + '/' + $(this).val().toLowerCase(), null, function(data)
                {
                    if (data.result[0]['count'] == 0)
                    {
                        $('#city').attr('disabled', 'disabled').val('No Cities For This Region').css('color', '#808080');
                    }
                    else
                    {
                        $('#city').removeAttr('disabled').css('color', '#000').val('Enter A City');
                    }
                });
            }
        }
        else
        {
            $('#city').attr('disabled', 'disabled').val('Enter A City').css('color', '#808080');
        }
    });

    $("#city").autocomplete({
        source: function(request, response) {
            if (cache.term == request.term && cache.content) {
                response(cache.content);
            }
            if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
                var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                response($.grep(cache.content, function(value) {
                    return matcher.test(value.value)
                }));
            }

            $.ajax({
                url: '/json/cities/' + $('#country').val().toLowerCase() + '/' + (($('#region').val() == '') ? '00' : $('#region').val()),
                dataType: "json",
                data: request,
                success: function(data) {
                    cache.term = request.term;
                    cache.content = data;
                    response(data);
                    
                    $.each(cache.content, function(i, val) {
                        if ($(this).val().toLowerCase() == val.value.toLowerCase())
                        {
                            found = true;
                            $(this).val(val.value);
                            $('#city_id').val(val.id);
                        }
                    });

                }
            });
        },
        minLength: 2,
        select: function(event, ui) {
            $('#city_id').val(ui.item.id);
        }
    });

    $('#city').focus(function() {
        if ($(this).val() == 'Enter A City')
        {
            $(this).val('');
        }
    });

/*    $("#city").blur( function() {
        var city = this;
        var found = false;

        $.each(cache.content, function(i, val) {
            if ($(city).val().toLowerCase() == val.value.toLowerCase())
            {
                found = true;
                $(city).val(val.value);
                $('#city_id').val(val.id);
            }
        });

        if (found == false)
        {
            $(city).val('');
        }
    });
*/
    $("#city").keypress(function (e) {   
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {   
            return false;   
        }
    });
});