/// <reference path="jquery.js" />

//gets the url and replaces the selected elements' HTML with the response
//param url: url of the page to get
//param selector: jQuery selector of the object(s) to fill with the response (i.e. #myDivId)
function ajaxGetToHtml(url,selector)
{
    $.get(url, function(data) { $(selector).html(data); });
}

//adds a favorite for the specified user
//param obj: the sending object (link)
//param gbuid: the gobiguserid of the user who is adding a favorite
//param fav_id: the gobiguserid or classifiedid of the user/classified being added as a favorite
var currObj;
function addFavorite(obj, gbuid, fav_id){
    if(!gbuid) return false;
    if(!obj) obj = this;
    if(!fav_id) fav_id = $(obj).attr('title');

    currObj = obj;
    
    if(fav_id!=''){
        //favSrc = $(obj).attr("id"); //this is the object that called the function.  Hide it when successful.
        UserFavoriteAdd.CreateFavorite(fav_id, gbuid, addFavorite_callback, obj);
    }
}

function addFavorite_callback(response){
    if (response != null && response.value != null) { 
        var succ = response.value;
        var favSrc = $(response.context);
        
        if(succ=='1'){
            $(favSrc).html('Added to favorites').click(function() {
                alert('This has already been added to your favorites.');
                return;
            });
            alert('This item has been added to your favorites. You can view/edit your favorites in the "My Favorites" section of your profile. To access your profile, click the "Profile" link at the top of this page. Once in your profile area, click on "My Favorites" located on the right side of the page.');
            $(currObj).unbind("click");
            $(currObj).bind("click", function() { alert('This has already been added to your favorites.'); });
        } else{
            if(window.console){
                console.log("AJAX ERROR: "+succ);
            }
            throw 'AJAX error in addFavorite_callback in GoBigCommon.js: ' + succ;
        }
    } else {
        alert('There was an error.  Please call 1-877-712-9040 to report the problem.'); 
    }
    
    return false;
    
}

function defaultButtonPanel_KeyPress()
{
    var k = event.which || window.event.keyCode;
    
    if(k == 13)
    {
        $(this).find('input.defaultButton').click();
        return false; //prevent other event handlers from firing
    }
    
    return true;
}

$(document).ready(function() {
    //$('.defaultButtonPanel input').keypress(defaultButtonPanel_KeyPress);
    $('.corner-round').corner('round');
});

//pass in selectors for the elements copied from and to
// only supports single select and input[type=text] inputs and textareas
function copyValue(from, to) {

    if (to == null) to = from;

    to = to.toString();

    $(to).each(function() {
        if ($(this).is('select')) {
            var val = $(from).filter('[value!=-1]:first').val();
            if (this.selectedIndex == 0 || $(this).is(':hidden') || $(this).parents(':hidden').length > 0) $(this).val(val);
        }
        else if ($(this).is('input[type=text],textarea')) {
            var val = $(from).filter('[value]:first').val();
            if ($(this).val().length == 0 || $(this).is(':hidden') || $(this).parents(':hidden').length > 0) $(this).val(val);
        }
    });
}

var path_to_root = (window.location.host == 'localhost') ? '/gbweb2/' : '/';

function delegate(that, thatMethod) {
    return function() { return thatMethod.call(that); }
}

function gb_alert(message, title, callback,no_buttons) {
    message = (message!=undefined) ? message.toString() : '';
    var div = $('.alertDiv').clone();
    $(div).find('.alertMessage').html(message.replace(/\n/g, '<br />').replace(/\*([^\s][^\n]*?)\*/g, '<b><u>$1</u></b>'));
    $(div).find('.alertTitle').html('<b>' + (title || '') + '</b>');
    if (no_buttons) $(div).find('.alertButtons').html('&nbsp;');
    if (!$.modal(div)) alert1(message, title);
    if (callback) {
		$(div).find('.simplemodal-close').one('click', function() { callback.call(); });
	}

	$(window).trigger('resize');

}

function gb_error(msg, url, line) {
    if (!url) url = window.location.toString();
    if (!msg) msg = 'no details provided';
    var sender = this || {id: 'unknown'};
    
    $.post(path_to_root + 'ajax/LogError.aspx', { msg: msg, url: url, line: line, sender: (sender.id || 'id unknown') });
    //alert('An error has occured and was reported to the administrators. Please try again or click "contact us" at the top right of the page for assistance.', 'Error');

    return false;
}

window.alert1 = window.alert;
window.alert = gb_alert;
//window.onerror = gb_error;



function WebForm_FireDefaultButton(event, target) {
    if (event.keyCode == 13) {
        var src = event.srcElement || event.target;
        if (!src || (src.tagName.toLowerCase() != "textarea")) {
            var defaultButton;
            if (__nonMSDOMBrowser) {
                defaultButton = document.getElementById(target);
            }
            else {
                defaultButton = document.all[target];
            }
            if (defaultButton && typeof (defaultButton.click) != "undefined") {
                defaultButton.click();
                event.cancelBubble = true;
                if (event.stopPropagation) event.stopPropagation();
                return false;
            }
        }
    }
    return true;
}


/*
* jQuery States plugin
* http://www.gobignetwork.com
* 
* Copyright (c) 2008 Go BIG Media, LLC, Erick Smith
* Licensed under the MIT License:
*   http://www.opensource.org/licenses/mit-license.php
* 
* Updated: 2008/05/16
* Version: 1.00
*/
(function($) {
    /**
    * States plugin allows for a statelist to be autopopulated based on the country list the plugin was applied to
    * 
    * This plug in will be applied to the country list.  An optional statelist reference can be passed if the statelist is not ID as 'state'.
    * 
    * @example  $('#countries').States($('#states'));
    * @desc Applies the change event to the countries dropdown and assigns the state population to the states dropdown
    * 
    * @example  $('#countries').States.Select({state: 'OH'});
    * @desc Populates the state list and sets it to OH
    * 
    * @example $('#countries').States.Select({state: 'OH', country: 'USA'});
    * @desc Populates the state list and sets it to OH, selects USA in the country list (in the event country is being populated elsewhere other than user selection)
    *
    * @name States
    * @param String (optional) Element to apply the state data population to.
    * @cat Plugins/States
    */
    $.fn.States = function(options) {

        var defaults = {
            statesList: $('#states'),
            country: null,
            state: null
        };

        $.extend(defaults, options);
        defaults.country = $(this);

        $(this).change(function() {
            Load(options);
        });

        $.fn.States.Reset = function() {
            $('option:first', defaults.country).attr('selected', 'true');
            defaults.statesList.attr('selectedIndex', '0');
        }

        $(this).States.Load = function(options) { Load(options) };

        function Load(options) {
            state = '';
            country = '';

            if (options) {
                state = (options.state) ? options.state : '';
                country = (options.country) ? options.country : '';
                if (country != '') {
                    $("option[@value='" + country + "']").attr('selected', 'true');
                } else {
                    country = $('option:selected', defaults.country).val();
                }
            }

            $.getJSON(path_to_root + 'ajax/GetStatesByCountry.aspx', { "country": country }, function(data) {
                defaults.statesList.empty();
                defaults.statesList.append("<option value=\"-1\">--</option>");
                for (var i = 0; i < data.states.length; i++) {
                    defaults.statesList.append("<option value=\"" + data.states[i] + "\">" + data.states[i] + "</option>");
                }
                if (state != '') {
                    $("option[@value='" + state + "']", defaults.statesList).attr('selected', 'true');
                } else {
                    defaults.statesList.attr('selectedIndex', '0');
                }
            });

        }

    }
})(jQuery);