$(function() {
// jQuery - DOM Ready
// -----------------------------------------------------------------------------

	
// Custom Fade behavior (probably not needed in jquery 1.4
// -----------------------------------------------------------------------------
$.fn.customFadeIn = function(speed, callback) {
	$(this).fadeIn(speed, function() {
		if(!$.support.opacity)
			$(this).get(0).style.removeAttribute('filter');
		if(callback != undefined)
			callback();
	});
};

$.fn.customFadeOut = function(speed, callback) {
	$(this).fadeOut(speed, function() {
		if(!$.support.opacity)
			$(this).get(0).style.removeAttribute('filter');
		if(callback != undefined)
			callback();
	});
};

$.fn.customFadeTo = function(speed,to,callback) {
	return this.animate({opacity: to}, speed, function() {
		if (to == 1 && jQuery.browser.msie)
			this.style.removeAttribute('filter');
		if (jQuery.isFunction(callback))
			callback();
	});
};

/* Set up tab order */
$(':input:not(option), a').each(function(i,e) { $(e).attr('tabindex', i); });
//$("input[type='text']:not('form#ask-expert input'):enabled:first").focus();

/**
 * jQuery.Waitbox
 * Date: 10/28/2009
 * @author Chadwick Dahlquist
 * @version 0.2
 * 
 * Generate a div positioned to overlay a jQuery selection.
 * Extra CSS styles can be applied to the '.waitbox' div
 *
 * @return an anonymous function to stop the waiting.
 **/
jQuery.fn.waitbox = function(options) {

    // default options to override
    var opts = jQuery.fn.extend({
        // milliseconds until timeout
        timeout: 60000,
        // callback function for the timeout
        onTimeout: null
    }, options);

    var all = [];

    this.each(function(i) {

        var elm = jQuery(this);
        var elm_op = elm.offsetParent();
        var elm_p = elm.position();
                        
        all.push(
            jQuery(document.createElement('div')).css({
                // default bg image of 1px black at 75% opacity
                'background-image': 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA1JREFUCNdjYGBg2A8AAMQAwMAxl3kAAAAASUVORK5CYII=)',
                'background-color': 'transparent', 
                'background-repeat': 'repeat', 
                'background-position': '50% 50%',
                'position': 'absolute',
                'top': elm_p.top,
                'left': elm_p.left,
                'width': elm.width(),
                'height': elm.height(),
                'z-index': 1000
            }).addClass('waitbox').appendTo(elm_op).get(0)
        );

    });

    var killAll = function() {
        jQuery(all).fadeOut(150, function() {
            jQuery(this).remove();
        });
    };

    var timeout = setTimeout(function() {
        if (opts.onTimeout) {
            opts.onTimeout.call();
        } else {
            alert("This site is not responding to your request. Please try again.");            
        }
        killAll.call();
    }, (opts.timeout));

    // Return an anonymous function that removes the waitbox(s) 
    // and stops the timeout clock
    return function() {
        clearTimeout(timeout);
        killAll.call();
    };
};

// Home page (home.html) rotating images
$("#value-fader").innerfade({
    speed: 500, 
    timeout: 6000
});


// Make hover work on select elements (for x-browser compat)
$("label").hover(function(evt){
    // Mouseover
    $(this).addClass("hover");
}, function(evt){
    // Mouseout
    $(this).removeClass("hover");
});


//Change location Form 
//Handle the modal dialog and ajax form behaviour
$(".change-location").simpleDialog({
 showCloseLabel: false,
 width: 690,
 open: function() {
     // The form element itself
     var form        = $("#change-location-form");
     // The fragment of the form that is dynamically updated
     var fragment    = $("#change-location-form-fragment");
     // Node to dynamically display and update upon error
     var div_error   = $("#change-location-form-error");
     // Node to dynamically display and update upon success
     var div_success = $("#change-location-form-success");
     
     // Clobber any positioning that puts dialog off-screen (dumb plugin)
     if (parseInt(this.css('top').replace("px", ""), 10) < 10) {
         this.css({top: 10});
     } 
     
     g_activate_masks();
     
     // Init the ajax form
     form.ajaxForm({
         dataType: 'json',
         beforeSubmit: function(data, form, opts) {
    	 	// Set current page
    	 	data[1].value = document.location;
    	 	
            // Waiting notice
    	 	this.stopWaiting = fragment.waitbox();
         },
         success: function(resp) {

             if (resp['redirect']) {
                 document.location = resp['redirect'];
                 // No need to call the callback as the page is disapearing. 
                 return false;
             }

             // Callback to stop the waiting notice
             if (this.stopWaiting) this.stopWaiting.call();
             // Clear the form fragment fields and update w/ new markup
             fragment.empty().append(resp['form_html']);

             // If the form is not valid
             if (resp['result'] == 'error') {
                 // Upon failure, update content and show this div (hard-coded)
                 div_error.show().children("p.error").empty().append(resp['text']);
                 g_activate_masks();
                 return false;
             }
             
             // Upon success, hide the form fields and error notices
             div_error.hide();
             // Upon success, update content and show this div (hard-coded)
             div_success.show().children("p.success").empty().append(resp['text']);
             
             return true;
         }
     });
 }
});

//Send feedback Form
//Handle the modal dialog and ajax form behaviour
$(".send-feedback").simpleDialog({
showCloseLabel: false,
width: 620,
open: function() {
   // The form element itself
   var form        = $("#send-feedback-form");
   // The fragment of the form that is dynamically updated
   var fragment    = $("#send-feedback-form-fragment");
   // Node to dynamically display and update upon error
   var div_error   = $("#send-feedback-form-error");
   // Node to dynazmically display and update upon success
   var div_success = $("#send-feedback-form-success");
   
   // Clobber any positioning that puts dialog off-screen (dumb plugin)
   if (parseInt(this.css('top').replace("px", ""), 10) < 10) {
       this.css({top: 10});
   } 
   
   g_activate_masks();
   
   // Init the ajax form
   form.ajaxForm({
       dataType: 'json',
       beforeSubmit: function(data, form, opts) {
        // Waiting notice
  	 	this.stopWaiting = fragment.waitbox();
       },
       success: function(resp) {

           // Callback to stop the waiting notice
           if (this.stopWaiting) this.stopWaiting.call();
           // Clear the form fragment fields and update w/ new markup
           fragment.empty().append(resp['form_html']);

           // If the form is not valid
           if (resp['result'] == 'error') {
               // Upon failure, update content and show this div (hard-coded)
               div_error.show().children("p.error").empty().append(resp['text']);
               g_activate_masks();
               return false;
           }
           
           // Upon success, hide the form fields and error notices
           div_error.hide();
           // Upon success, update content and show this div (hard-coded)
           div_success.show().children("p.success").empty().append(resp['text']);
           
           return true;
       }
   });
}
});
$("table.topics-list tr td a").truncate({
    max_length: 26,
    more: '…',
    // Custom hack (see source, sorry)
    skip_dynamic_foofoo: true
});

// Links inside forms with class `submit` will submit the form 
$("form a.submit").click(function(evt) {
    $(this).parents("form:first")[0].submit(); return false;
});

// Initialize widgets that have been defined in ./widgets.js
// ---------------------------------------------------------
$(".button-supreme.spinner").SubmitSpinner({
    active_class: "waiting",
    message: "Submitting",
    // 30 seconds
    timeout: 30000
}); 
$("input[placeholder], textarea[placeholder]").PlaceholderInput();
$("form#ask-expert").AskExpertForm(); 

// Blur any buttons on click (to prevent ugly outlines in FF)
//---------------------------------------------------------
$(".button-primary input, .button-secondary input, .button-supreme input," +
  ".button-primary a, .button-secondary a, .button-supreme a")
  	.click(function (){ this.blur(); })
  	.mouseout(function (){ this.blur(); });

// Ordered list steps automatic class incrementing
$("ol.steps li").each(function(i, li) {
    $(li).addClass("step_" + (i+1));
});

// Account news page badges
$("table#badge-selector tr.code td").each(function(i, td) {
    // Automatically select all text upon click/focus
    $("input", td).bind('click focus', function(evt) { this.select(); });
});

// -----------------------------------------------------------------------------
}); // END jQuery - DOM Ready
