/*
 * jQuery Easing Compatibility v1 - http://gsgd.co.uk/sandbox/jquery.easing.php
 *
 * Adds compatibility for applications that use the pre 1.2 easing names
 *
 * Copyright (c) 2007 George Smith
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

jQuery.extend( jQuery.easing,
{
	easeIn: function (x, t, b, c, d) {
		return jQuery.easing.easeInQuad(x, t, b, c, d);
	},
	easeOut: function (x, t, b, c, d) {
		return jQuery.easing.easeOutQuad(x, t, b, c, d);
	},
	easeInOut: function (x, t, b, c, d) {
		return jQuery.easing.easeInOutQuad(x, t, b, c, d);
	},
	expoin: function(x, t, b, c, d) {
		return jQuery.easing.easeInExpo(x, t, b, c, d);
	},
	expoout: function(x, t, b, c, d) {
		return jQuery.easing.easeOutExpo(x, t, b, c, d);
	},
	expoinout: function(x, t, b, c, d) {
		return jQuery.easing.easeInOutExpo(x, t, b, c, d);
	},
	bouncein: function(x, t, b, c, d) {
		return jQuery.easing.easeInBounce(x, t, b, c, d);
	},
	bounceout: function(x, t, b, c, d) {
		return jQuery.easing.easeOutBounce(x, t, b, c, d);
	},
	bounceinout: function(x, t, b, c, d) {
		return jQuery.easing.easeInOutBounce(x, t, b, c, d);
	},
	elasin: function(x, t, b, c, d) {
		return jQuery.easing.easeInElastic(x, t, b, c, d);
	},
	elasout: function(x, t, b, c, d) {
		return jQuery.easing.easeOutElastic(x, t, b, c, d);
	},
	elasinout: function(x, t, b, c, d) {
		return jQuery.easing.easeInOutElastic(x, t, b, c, d);
	},
	backin: function(x, t, b, c, d) {
		return jQuery.easing.easeInBack(x, t, b, c, d);
	},
	backout: function(x, t, b, c, d) {
		return jQuery.easing.easeOutBack(x, t, b, c, d);
	},
	backinout: function(x, t, b, c, d) {
		return jQuery.easing.easeInOutBack(x, t, b, c, d);
	}
});

/*
 * Facebox (for jQuery)
 * version: 1.2 (05/05/2008)
 * @requires jQuery v1.2 or later
 *
 * Examples at http://famspam.com/facebox/
 *
 * Licensed under the MIT:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
 *
 * Usage:
 *  
 *  jQuery(document).ready(function() {
 *    jQuery('a[rel*=facebox]').facebox() 
 *  })
 *
 *  <a href="#terms" rel="facebox">Terms</a>
 *    Loads the #terms div in the box
 *
 *  <a href="terms.html" rel="facebox">Terms</a>
 *    Loads the terms.html page in the box
 *
 *  <a href="terms.png" rel="facebox">Terms</a>
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 * 
 *    jQuery.facebox('some html')
 *
 *  The above will open a facebox with "some html" as the content.
 *    
 *    jQuery.facebox(function($) { 
 *      $.get('blah.html', function(data) { $.facebox(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The facebox function can also display an ajax page or image:
 *  
 *    jQuery.facebox({ ajax: 'remote.html' })
 *    jQuery.facebox({ image: 'dude.jpg' })
 *
 *  Want to close the facebox?  Trigger the 'close.facebox' document event:
 *
 *    jQuery(document).trigger('close.facebox')
 *
 *  Facebox also has a bunch of other hooks:
 *
 *    loading.facebox
 *    beforeReveal.facebox
 *    reveal.facebox (aliased as 'afterReveal.facebox')
 *    init.facebox
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
 *
 */
(function($) {
  $.facebox = function(data, klass) {
    $.facebox.loading()

    if (data.ajax) fillFaceboxFromAjax(data.ajax)
    else if (data.image) fillFaceboxFromImage(data.image)
    else if (data.div) fillFaceboxFromHref(data.div)
    else if ($.isFunction(data)) data.call($)
    else $.facebox.reveal(data, klass)
  }

  /*
   * Public, $.facebox methods
   */

  $.extend($.facebox, {
    settings: {
      opacity      : 0,
      overlay      : true,
      loadingImage :  SK_ASSET_HOST + '/images/layout/facebox/loading.gif',
      closeImage   :  SK_ASSET_HOST + '/images/layout/facebox/close.png',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      faceboxHtml  : '\
    <div id="facebox" style="display:none;"> \
      <a href="#" class="close"> \
      </a> \
      <div class="popup"> \
        <table> \
          <tbody> \
            <tr> \
              <td class="tl"/><td class="b"/><td class="tr"/> \
            </tr> \
            <tr> \
              <td class="b"/> \
              <td class="body"> \
                <div class="content"> \
                </div> \
              </td> \
              <td class="b"/> \
            </tr> \
            <tr> \
              <td class="bl"/><td class="b"/><td class="br"/> \
            </tr> \
          </tbody> \
        </table> \
      </div> \
    </div>'
    },

    loading: function() {
      init()
      if ($('#facebox .loading').length == 1) return true
      showOverlay()

      $('#facebox .content').empty()
      $('#facebox .body').children().hide().end().
        append('<div class="loading"><img src="'+ $.facebox.settings.loadingImage + '"/></div>')
      $('#facebox').css({
        top:	getPageScroll()[1] + 72,
        left:	($(window).width() / 2) - 100
      }).show()

      $(document).bind('keydown.facebox', function(e) {
        if (e.keyCode == 27) $.facebox.close()
        return true
      })
      $(document).trigger('loading.facebox')
    },

    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.facebox')
      if (klass) $('#facebox .content').addClass(klass)
      $('#facebox .content').append(data)
      $('#facebox .loading').remove()
      $('#facebox .body').children().fadeIn('normal')
      $('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2))
      $(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
    },

    close: function() {
      $(document).trigger('close.facebox')
      return false
    }
  })

  /*
   * Public, $.fn methods
   */

  $.fn.facebox = function(settings) {
    init(settings)

    function clickHandler() {
      $.facebox.loading(true)

      // support for rel="facebox.inline_popup" syntax, to add a class
      // also supports deprecated "facebox[.inline_popup]" syntax
      var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      fillFaceboxFromHref(this.href, klass)
      return false
    }

    return this.click(clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup facebox on this page
  function init(settings) {
    if ($.facebox.settings.inited) return true
    else $.facebox.settings.inited = true

    $(document).trigger('init.facebox')
    makeCompatible()

    var imageTypes = $.facebox.settings.imageTypes.join('|')
    $.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')

    if (settings) $.extend($.facebox.settings, settings)
    $('body').append($.facebox.settings.faceboxHtml)

    var preload = [ new Image(), new Image() ]
    preload[0].src = $.facebox.settings.closeImage
    preload[1].src = $.facebox.settings.loadingImage

    $('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#facebox .close').click($.facebox.close)
  }
  
  // getPageScroll() by quirksmode.com
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;	
    }
    return new Array(xScroll,yScroll) 
  }

  // Adapted from getPageSize() by quirksmode.com
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }	
    return windowHeight
  }

  // Backwards compatibility
  function makeCompatible() {
    var $s = $.facebox.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: blah.extension
  //    ajax: anything else
  function fillFaceboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      $.facebox.reveal($(target).clone().show(), klass)

    // image
    } else if (href.match($.facebox.settings.imageTypesRegexp)) {
      fillFaceboxFromImage(href, klass)
    // ajax
    } else {
      fillFaceboxFromAjax(href, klass)
    }
  }

  function fillFaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
    }
    image.src = href
  }

  function fillFaceboxFromAjax(href, klass) {
    $.get(href, function(data) { $.facebox.reveal(data, klass) })
  }

  function skipOverlay() {
    return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null 
  }

  function showOverlay() {
    if (skipOverlay()) return

    if ($('facebox_overlay').length == 0) 
      $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')

    $('#facebox_overlay').hide().addClass("facebox_overlayBG")
      .css('opacity', $.facebox.settings.opacity)
      .click(function() { $(document).trigger('close.facebox') })
      .fadeIn(200)
    return false
  }

  function hideOverlay() {
    if (skipOverlay()) return

    $('#facebox_overlay').fadeOut(200, function(){
      $("#facebox_overlay").removeClass("facebox_overlayBG")
      $("#facebox_overlay").addClass("facebox_hide") 
      $("#facebox_overlay").remove()
    })
    
    return false
  }

  /*
   * Bindings
   */

  $(document).bind('close.facebox', function() {
    $(document).unbind('keydown.facebox')
    $('#facebox').fadeOut(function() {
      $('#facebox .content').removeClass().addClass('content')
      hideOverlay()
      $('#facebox .loading').remove()
    })
  })

})(jQuery);

/*
 * jQuery Form Plugin
 * version: 2.18 (06-JAN-2009)
 * @requires jQuery v1.2.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id$
 */
;(function($) {

/*
    Usage Note:  
    -----------
    Do not use both ajaxSubmit and ajaxForm on the same form.  These
    functions are intended to be exclusive.  Use ajaxSubmit if you want
    to bind your own submit handler to the form.  For example,

    $(document).ready(function() {
        $('#myForm').bind('submit', function() {
            $(this).ajaxSubmit({
                target: '#output'
            });
            return false; // <-- important!
        });
    });

    Use ajaxForm when you want the plugin to manage all the event binding
    for you.  For example,

    $(document).ready(function() {
        $('#myForm').ajaxForm({
            target: '#output'
        });
    });
        
    When using ajaxForm, the ajaxSubmit function will be invoked for you
    at the appropriate time.  
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting 
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
    // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
    if (!this.length) {
        log('ajaxSubmit: skipping submit process - no element selected');
        return this;
    }

    if (typeof options == 'function')
        options = { success: options };

    options = $.extend({
        url:  this.attr('action') || window.location.toString(),
        type: this.attr('method') || 'GET'
    }, options || {});

    // hook for manipulating the form data before it is extracted;
    // convenient for use with rich editors like tinyMCE or FCKEditor
    var veto = {};
    this.trigger('form-pre-serialize', [this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
        return this;
    }

    // provide opportunity to alter form data before it is serialized
    if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSerialize callback');
        return this;
    }    
   
    var a = this.formToArray(options.semantic);
    if (options.data) {
        options.extraData = options.data;
        for (var n in options.data) {
          if(options.data[n] instanceof Array) {
            for (var k in options.data[n])
              a.push( { name: n, value: options.data[n][k] } )
          }  
          else
             a.push( { name: n, value: options.data[n] } );
        }
    }

    // give pre-submit callback an opportunity to abort the submit
    if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSubmit callback');
        return this;
    }    

    // fire vetoable 'validate' event
    this.trigger('form-submit-validate', [a, this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
        return this;
    }    

    var q = $.param(a);

    if (options.type.toUpperCase() == 'GET') {
        options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
        options.data = null;  // data is null for 'get'
    }
    else
        options.data = q; // data is the query string for 'post'

    var $form = this, callbacks = [];
    if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
    if (options.clearForm) callbacks.push(function() { $form.clearForm(); });

    // perform a load on the target only if dataType is not provided
    if (!options.dataType && options.target) {
        var oldSuccess = options.success || function(){};
        callbacks.push(function(data) {
            $(options.target).html(data).each(oldSuccess, arguments);
        });
    }
    else if (options.success)
        callbacks.push(options.success);

    options.success = function(data, status) {
        for (var i=0, max=callbacks.length; i < max; i++)
            callbacks[i].apply(options, [data, status, $form]);
    };

    // are there files to upload?
    var files = $('input:file', this).fieldValue();
    var found = false;
    for (var j=0; j < files.length; j++)
        if (files[j])
            found = true;

    // options.iframe allows user to force iframe mode
   if (options.iframe || found) { 
       // hack to fix Safari hang (thanks to Tim Molendijk for this)
       // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
       if ($.browser.safari && options.closeKeepAlive)
           $.get(options.closeKeepAlive, fileUpload);
       else
           fileUpload();
       }
   else
       $.ajax(options);

    // fire 'notify' event
    this.trigger('form-submit-notify', [this, options]);
    return this;


    // private function for handling file uploads (hat tip to YAHOO!)
    function fileUpload() {
        var form = $form[0];
        
        if ($(':input[name=submit]', form).length) {
            alert('Error: Form elements must not be named "submit".');
            return;
        }
        
        var opts = $.extend({}, $.ajaxSettings, options);
		var s = jQuery.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);

        var id = 'jqFormIO' + (new Date().getTime());
        var $io = $('<iframe id="' + id + '" name="' + id + '" />');
        var io = $io[0];

        if ($.browser.msie || $.browser.opera) 
            io.src = 'javascript:false;document.write("");';
        $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

        var xhr = { // mock object
            aborted: 0,
            responseText: null,
            responseXML: null,
            status: 0,
            statusText: 'n/a',
            getAllResponseHeaders: function() {},
            getResponseHeader: function() {},
            setRequestHeader: function() {},
            abort: function() { 
                this.aborted = 1; 
                $io.attr('src','about:blank'); // abort op in progress
            }
        };

        var g = opts.global;
        // trigger ajax global events so that activity/block indicators work like normal
        if (g && ! $.active++) $.event.trigger("ajaxStart");
        if (g) $.event.trigger("ajaxSend", [xhr, opts]);

		if (s.beforeSend && s.beforeSend(xhr, s) === false) {
			s.global && jQuery.active--;
			return;
        }
        if (xhr.aborted)
            return;
        
        var cbInvoked = 0;
        var timedOut = 0;

        // add submitting element to data if we know it
        var sub = form.clk;
        if (sub) {
            var n = sub.name;
            if (n && !sub.disabled) {
                options.extraData = options.extraData || {};
                options.extraData[n] = sub.value;
                if (sub.type == "image") {
                    options.extraData[name+'.x'] = form.clk_x;
                    options.extraData[name+'.y'] = form.clk_y;
                }
            }
        }

        // take a breath so that pending repaints get some cpu time before the upload starts
        setTimeout(function() {
            // make sure form attrs are set
            var t = $form.attr('target'), a = $form.attr('action');
            $form.attr({
                target:   id,
                method:   'POST',
                action:   opts.url
            });
            
            // ie borks in some cases when setting encoding
            if (! options.skipEncodingOverride) {
                $form.attr({
                    encoding: 'multipart/form-data',
                    enctype:  'multipart/form-data'
                });
            }

            // support timout
            if (opts.timeout)
                setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

            // add "extra" data to form if provided in options
            var extraInputs = [];
            try {
                if (options.extraData)
                    for (var n in options.extraData)
                        extraInputs.push(
                            $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
                                .appendTo(form)[0]);
            
                // add iframe to doc and submit the form
                $io.appendTo('body');
                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
                form.submit();
            }
            finally {
                // reset attrs and remove "extra" input elements
                $form.attr('action', a);
                t ? $form.attr('target', t) : $form.removeAttr('target');
                $(extraInputs).remove();
            }
        }, 10);

        function cb() {
            if (cbInvoked++) return;
            
            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

            var operaHack = 0;
            var ok = true;
            try {
                if (timedOut) throw 'timeout';
                // extract the server response from the iframe
                var data, doc;

                doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
                
                if (doc.body == null && !operaHack && $.browser.opera) {
                    // In Opera 9.2.x the iframe DOM is not always traversable when
                    // the onload callback fires so we give Opera 100ms to right itself
                    operaHack = 1;
                    cbInvoked--;
                    setTimeout(cb, 100);
                    return;
                }
                
                xhr.responseText = doc.body ? doc.body.innerHTML : null;
                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
                xhr.getResponseHeader = function(header){
                    var headers = {'content-type': opts.dataType};
                    return headers[header];
                };

                if (opts.dataType == 'json' || opts.dataType == 'script') {
                    var ta = doc.getElementsByTagName('textarea')[0];
                    xhr.responseText = ta ? ta.value : xhr.responseText;
                }
                else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
                    xhr.responseXML = toXml(xhr.responseText);
                }
                data = $.httpData(xhr, opts.dataType);
            }
            catch(e){
                ok = false;
                $.handleError(opts, xhr, 'error', e);
            }

            // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
            if (ok) {
                opts.success(data, 'success');
                if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
            }
            if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
            if (g && ! --$.active) $.event.trigger("ajaxStop");
            if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

            // clean up
            setTimeout(function() {
                $io.remove();
                xhr.responseXML = null;
            }, 100);
        };

        function toXml(s, doc) {
            if (window.ActiveXObject) {
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = 'false';
                doc.loadXML(s);
            }
            else
                doc = (new DOMParser()).parseFromString(s, 'text/xml');
            return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
        };
    };
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *    is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *    used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */ 
$.fn.ajaxForm = function(options) {
    return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
        $(this).ajaxSubmit(options);
        return false;
    }).each(function() {
        // store options in hash
        $(":submit,input:image", this).bind('click.form-plugin',function(e) {
            var form = this.form;
            form.clk = this;
            if (this.type == 'image') {
                if (e.offsetX != undefined) {
                    form.clk_x = e.offsetX;
                    form.clk_y = e.offsetY;
                } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
                    var offset = $(this).offset();
                    form.clk_x = e.pageX - offset.left;
                    form.clk_y = e.pageY - offset.top;
                } else {
                    form.clk_x = e.pageX - this.offsetLeft;
                    form.clk_y = e.pageY - this.offsetTop;
                }
            }
            // clear form vars
            setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 10);
        });
    });
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
    this.unbind('submit.form-plugin');
    return this.each(function() {
        $(":submit,input:image", this).unbind('click.form-plugin');
    });

};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
    var a = [];
    if (this.length == 0) return a;

    var form = this[0];
    var els = semantic ? form.getElementsByTagName('*') : form.elements;
    if (!els) return a;
    for(var i=0, max=els.length; i < max; i++) {
        var el = els[i];
        var n = el.name;
        if (!n) continue;

        if (semantic && form.clk && el.type == "image") {
            // handle image inputs on the fly when semantic == true
            if(!el.disabled && form.clk == el)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
            continue;
        }

        var v = $.fieldValue(el, true);
        if (v && v.constructor == Array) {
            for(var j=0, jmax=v.length; j < jmax; j++)
                a.push({name: n, value: v[j]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: n, value: v});
    }

    if (!semantic && form.clk) {
        // input type=='image' are not found in elements array! handle them here
        var inputs = form.getElementsByTagName("input");
        for(var i=0, max=inputs.length; i < max; i++) {
            var input = inputs[i];
            var n = input.name;
            if(n && !input.disabled && input.type == "image" && form.clk == input)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
        }
    }
    return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
    //hand off to jQuery.param for proper encoding
    return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
    var a = [];
    this.each(function() {
        var n = this.name;
        if (!n) return;
        var v = $.fieldValue(this, successful);
        if (v && v.constructor == Array) {
            for (var i=0,max=v.length; i < max; i++)
                a.push({name: n, value: v[i]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: this.name, value: v});
    });
    //hand off to jQuery.param for proper encoding
    return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *      <input name="A" type="text" />
 *      <input name="A" type="text" />
 *      <input name="B" type="checkbox" value="B1" />
 *      <input name="B" type="checkbox" value="B2"/>
 *      <input name="C" type="radio" value="C1" />
 *      <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *       array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
    for (var val=[], i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = $.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
            continue;
        v.constructor == Array ? $.merge(val, v) : val.push(v);
    }
    return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;

    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
            return null;

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
                // extra pain for IE...
                var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
    return this.each(function() {
        $('input,select,textarea', this).clearFields();
    });
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox' || t == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) { 
    if (b == undefined) b = true;
    return this.each(function() { 
        this.disabled = !b 
    });
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
    if (select == undefined) select = true;
    return this.each(function() { 
        var t = this.type;
        if (t == 'checkbox' || t == 'radio')
            this.checked = select;
        else if (this.tagName.toLowerCase() == 'option') {
            var $sel = $(this).parent('select');
            if (select && $sel[0] && $sel[0].type == 'select-one') {
                // deselect all other options
                $sel.find('option').selected(false);
            }
            this.selected = select;
        }
    });
};

// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
    if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
        window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};

})(jQuery);


/*! Copyright (c) 2008 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version: 1.0.3
 * Requires jQuery 1.1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */

(function($) {
	
$.extend($.fn, {
	livequery: function(type, fn, fn2) {
		var self = this, q;
		
		// Handle different call patterns
		if ($.isFunction(type))
			fn2 = fn, fn = type, type = undefined;
			
		// See if Live Query already exists
		$.each( $.livequery.queries, function(i, query) {
			if ( self.selector == query.selector && self.context == query.context &&
				type == query.type && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) )
					// Found the query, exit the each loop
					return (q = query) && false;
		});
		
		// Create new Live Query if it wasn't found
		q = q || new $.livequery(this.selector, this.context, type, fn, fn2);
		
		// Make sure it is running
		q.stopped = false;
		
		// Run it immediately for the first time
		q.run();
		
		// Contnue the chain
		return this;
	},
	
	expire: function(type, fn, fn2) {
		var self = this;
		
		// Handle different call patterns
		if ($.isFunction(type))
			fn2 = fn, fn = type, type = undefined;
			
		// Find the Live Query based on arguments and stop it
		$.each( $.livequery.queries, function(i, query) {
			if ( self.selector == query.selector && self.context == query.context && 
				(!type || type == query.type) && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) && !this.stopped )
					$.livequery.stop(query.id);
		});
		
		// Continue the chain
		return this;
	}
});

$.livequery = function(selector, context, type, fn, fn2) {
	this.selector = selector;
	this.context  = context || document;
	this.type     = type;
	this.fn       = fn;
	this.fn2      = fn2;
	this.elements = [];
	this.stopped  = false;
	
	// The id is the index of the Live Query in $.livequery.queries
	this.id = $.livequery.queries.push(this)-1;
	
	// Mark the functions for matching later on
	fn.$lqguid = fn.$lqguid || $.livequery.guid++;
	if (fn2) fn2.$lqguid = fn2.$lqguid || $.livequery.guid++;
	
	// Return the Live Query
	return this;
};

$.livequery.prototype = {
	stop: function() {
		var query = this;
		
		if ( this.type )
			// Unbind all bound events
			this.elements.unbind(this.type, this.fn);
		else if (this.fn2)
			// Call the second function for all matched elements
			this.elements.each(function(i, el) {
				query.fn2.apply(el);
			});
			
		// Clear out matched elements
		this.elements = [];
		
		// Stop the Live Query from running until restarted
		this.stopped = true;
	},
	
	run: function() {
		// Short-circuit if stopped
		if ( this.stopped ) return;
		var query = this;
		
		var oEls = this.elements,
			els  = $(this.selector, this.context),
			nEls = els.not(oEls);
		
		// Set elements to the latest set of matched elements
		this.elements = els;
		
		if (this.type) {
			// Bind events to newly matched elements
			nEls.bind(this.type, this.fn);
			
			// Unbind events to elements no longer matched
			if (oEls.length > 0)
				$.each(oEls, function(i, el) {
					if ( $.inArray(el, els) < 0 )
						$.event.remove(el, query.type, query.fn);
				});
		}
		else {
			// Call the first function for newly matched elements
			nEls.each(function() {
				query.fn.apply(this);
			});
			
			// Call the second function for elements no longer matched
			if ( this.fn2 && oEls.length > 0 )
				$.each(oEls, function(i, el) {
					if ( $.inArray(el, els) < 0 )
						query.fn2.apply(el);
				});
		}
	}
};

$.extend($.livequery, {
	guid: 0,
	queries: [],
	queue: [],
	running: false,
	timeout: null,
	
	checkQueue: function() {
		if ( $.livequery.running && $.livequery.queue.length ) {
			var length = $.livequery.queue.length;
			// Run each Live Query currently in the queue
			while ( length-- )
				$.livequery.queries[ $.livequery.queue.shift() ].run();
		}
	},
	
	pause: function() {
		// Don't run anymore Live Queries until restarted
		$.livequery.running = false;
	},
	
	play: function() {
		// Restart Live Queries
		$.livequery.running = true;
		// Request a run of the Live Queries
		$.livequery.run();
	},
	
	registerPlugin: function() {
		$.each( arguments, function(i,n) {
			// Short-circuit if the method doesn't exist
			if (!$.fn[n]) return;
			
			// Save a reference to the original method
			var old = $.fn[n];
			
			// Create a new method
			$.fn[n] = function() {
				// Call the original method
				var r = old.apply(this, arguments);
				
				// Request a run of the Live Queries
				$.livequery.run();
				
				// Return the original methods result
				return r;
			}
		});
	},
	
	run: function(id) {
		if (id != undefined) {
			// Put the particular Live Query in the queue if it doesn't already exist
			if ( $.inArray(id, $.livequery.queue) < 0 )
				$.livequery.queue.push( id );
		}
		else
			// Put each Live Query in the queue if it doesn't already exist
			$.each( $.livequery.queries, function(id) {
				if ( $.inArray(id, $.livequery.queue) < 0 )
					$.livequery.queue.push( id );
			});
		
		// Clear timeout if it already exists
		if ($.livequery.timeout) clearTimeout($.livequery.timeout);
		// Create a timeout to check the queue and actually run the Live Queries
		$.livequery.timeout = setTimeout($.livequery.checkQueue, 20);
	},
	
	stop: function(id) {
		if (id != undefined)
			// Stop are particular Live Query
			$.livequery.queries[ id ].stop();
		else
			// Stop all Live Queries
			$.each( $.livequery.queries, function(id) {
				$.livequery.queries[ id ].stop();
			});
	}
});

// Register core DOM manipulation methods
$.livequery.registerPlugin('append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove');

// Run Live Queries when the Document is ready
$(function() { $.livequery.play(); });


// Save a reference to the original init method
var init = $.prototype.init;

// Create a new init method that exposes two new properties: selector and context
$.prototype.init = function(a,c) {
	// Call the original init and save the result
	var r = init.apply(this, arguments);
	
	// Copy over properties if they exist already
	if (a && a.selector)
		r.context = a.context, r.selector = a.selector;
		
	// Set properties
	if ( typeof a == 'string' )
		r.context = c || document, r.selector = a;
	
	// Return the result
	return r;
};

// Give the init function the jQuery prototype for later instantiation (needed after Rev 4091)
$.prototype.init.prototype = $.prototype;
	
})(jQuery);

var SK      = {version: "3.0 beta"};
    SK.FB   = {version: "0.1"}; // Facebook Scope
    SK.g    = {version: "0.1"}; // Google Scope
    SK.ajax = {version: "0.1"}; // Ajax Scope

// has dependency in admin + comments.js, leave for now.
function stopAnd(fn) {
  return function(e) {
    fn(e);
    return false;
  };
}

SK.core = {
  
  //# Resource URI Transformation
  ajaxifyResource: function (uri) {
    if (uri.search("\\.js") != -1) return uri;
    
    var insertionIndex = (uri.search("\\?") == -1 ? uri.length : uri.search("\\?"));
    var ajaxifiedAction = uri.substr(0, insertionIndex) + ".js" + uri.substr(insertionIndex);
    return ajaxifiedAction;
  },
  
  deAjaxifiedResource: function (uri) {
    if (uri.search("\\.js") == -1) return uri;

    var deAjaxifiedAction = uri.replace(/.js/, "");
    return deAjaxifiedAction;
  },
  
  ajaxifyActionAttribute: function (target, attr) {
    var action = $(target).attr(attr);
    $(target).attr(attr, this.ajaxifyResource(action));
  },
  
  deAjaxifyActionAttribute: function (target, attr) {
    var action = $(target).attr(attr);
    $(target).attr(attr, this.deAjaxifiedResource(action));
  },
  
  //# DOM Enhancements
  enableDefaultValueFor: function (input) {
    $(input).attr("defaultvalue", $(input).val());
    $(input).addClass("inactive");
    
    $(input).focus(
      function () { if ($(this).val() == $(this).attr("defaultvalue")) $(this).val('').addClass('active'); }
    );
    $(input).blur(
      function () { if ($(this).val() == '') $(this).val($(this).attr("defaultvalue")).removeClass('active'); }
    );
  },
  
  enableAutocompleteFor: function (input, options) {
    $(input).autocomplete(options.url, {  
      maxItemsToShow: 10,
      minChars: 4,
      selectFirst: true
    });
  },
  
  // options look like:
  // {buttonSelector:"#selector", revealTarget:"#selector", cssClass:"open", closeTargets:"#selector"}
  enableToggleRevealFor: function (options) {
    var selector      = options.buttonSelector;
    var target        = options.revealTarget;
    var css_class     = options.cssClass;
    var close_targets = options.closeTargets ? options.closeTargets : false;
    var return_value  = options.returnValue ? options.returnValue : false;
    
    // remove existing behaviour from a toggle
    $(selector).attr("onclick", "");
    
    $(selector).bind("click", function () {
      $(target).toggleClass(css_class);
      return return_value;
    });
    if (close_targets != false) {
      $(close_targets).bind("click", function () {
        $(target).toggleClass(css_class);
      });
    }
  },
  
  //# Remaining Characters
  // Use to display a warning next to a field of how many characters
  // are remaining in the allowed length. E.g. edit venue description,
  // leave message on User profile.
  maxCharsFor: function (fieldSelector, messageDivSelector, maxLength, the_appendage) {
    var appendage;
    the_appendage == undefined ? (appendage = " characters remaining") : (appendage = the_appendage);
    if ($(fieldSelector).length == 0) return;
    
    var updateFunc = function () {
      var descriptionLength = $(fieldSelector).val().length;
      var charsRemaining = maxLength - descriptionLength;
      
      var message = charsRemaining + appendage;
      $(messageDivSelector).text(message).removeAttr("class");
      if (charsRemaining < 1) {
        $(messageDivSelector).addClass("critical");
        SK.core.disableSubmitsForParentOf(fieldSelector);        
      } else if (charsRemaining < 100) {
        $(messageDivSelector).addClass("warning");
        SK.core.enableSubmitsForParentOf(fieldSelector);
      } else {
        SK.core.enableSubmitsForParentOf(fieldSelector);
      }
    };
    
    $(fieldSelector).keyup(updateFunc);
    updateFunc();
  },

  disableSubmitsForParentOf: function (aSelector) {
    $(aSelector).parents("form").find("input[type=submit]").attr("disabled", "disabled");
    $(aSelector).parents("form").find("input[type=submit]").addClass("disabled-submit");
  },
  
  enableSubmitsForParentOf: function (aSelector) {
    $(aSelector).parents("form").find("input[type=submit]").removeAttr("disabled");
    $(aSelector).parents("form").find("input[type=submit]").removeClass("disabled-submit");
  },
  
  // SK.core.enableSelectAllWith({
  //   control: "#acontrol",
  //   targets: "#target li input"
  // })
  enableSelectAllWith: function (options) {
    var control = options.control;
    var targets = options.targets;
    var numTargets = $(targets).length;
    
    var selectAll = function (targets) {
      $(targets).each(function (i, cb) {
        if ($(cb).attr("checked") == false) $(cb).attr("checked", true);
      });
    };
    
    var deselectAll = function (targets) {
      $(targets).each(function (i, cb) {
        if ($(cb).attr("checked")) $(cb).attr("checked", false);
      });
    };
    
    $(targets).bind("click", function () {
      var currentNumSelected = $(targets + ":checked").length;
      if (currentNumSelected == numTargets) {
        $(control).attr("checked", true);
        SK.core.enableSubmitsForParentOf(control);
      } else {
        $(control).attr("checked", false);
      }
    });
    
    $(control).bind("click", function () {
      if ($(control).attr("checked")) {
        selectAll(targets);
      } else {
        deselectAll(targets);
      }
    });
  },
  
  disableFormIfNoValuesFor: function (form) {
    var fields = $(form).find("input[type=text], input[type=checkbox], input[type=radio], textarea").not(".non_user_input");
    
    var performCheck = function (field) {
      SK.core.checkForUserValueInFields(fields) ? 
        SK.core.enableSubmitsForParentOf($(field)) : 
        SK.core.disableSubmitsForParentOf($(field));
    };
    
    fields.each(function (i, field) {
      switch ($(field).attr("type")) {
        case "checkbox":
        case "radio":
          $(field).bind("click", function () { performCheck(field); });
          performCheck(field);
          break;
        default:
          $(field).bind("blur", function () { performCheck(field); });
          performCheck(field);
          break;
      }
    });
     
  },
  
  checkForUserValueInFields: function (fields) {
    for (var i = 0; i < fields.length; i++) {
      switch ($(fields[i]).attr("type")) {
        case "checkbox":
        case "radio":
          if ($(fields[i]).attr("checked") == true) return true;
          break;
        default:
          if ($(fields[i]).attr("value") != "") return true;
          break;
      }
    }
    return false;
  },
  
  // usage:
  // SK.core.replaceSubmitWithLink({
  //   target: "#aSubmit",
  //   replacement: "Something to replace it with" // optional, if not provided will use target's "value" atrribute as link
  // })
  replaceSubmitWithLink: function (options) {
    var target      = options.target;
    var replacement = options.replacement ? options.replacement : false;
    var theform     = $(target).parents("form");
    
    var link = replacement ? $(replacement) : $("<a href=\"#\">" + $(target).attr("value") + "</a>");
    link.bind("click", function (e) {
      e.preventDefault();
      theform.trigger("submit");
      return false;
    });
    
    $(target).replaceWith(link); 
  },
  
  replacePNGWithGifForIE6: function () {
    $("img.ie6replaceme").each(function (i, img) {
      $(img).attr("src", $(img).attr("src").replace(/.png/, ".gif"));
    });
  },
  
  // parseUri 1.2.2
  // (c) Steven Levithan <stevenlevithan.com>
  // MIT License

  parseUri: {
    parse: function (str) {
      var	o   = SK.core.parseUri.options,
        m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
        uri = {},
        i   = 14;

      while (i--) uri[o.key[i]] = m[i] || "";
      
      uri[o.q.name] = {};
      uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
      });
      
      return uri;

    },

    options: {
      strictMode: false,
      key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],
      q:   {
        name:   "queryKey",
        parser: /(?:^|&)([^&=]*)=?([^&]*)/g
      },
      parser: {
        strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
        loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
      }

    }
  }
  
};

//# Search
SK.searchSetup = {
  searchBox: '#site-search-box',
  
  init: function() {
    if ($.browser.webkit) {
      $(searchBox)[0].type = 'search';
      $(searchBox).attr('results','5');
      $(searchBox).attr('autosave','com.songkick.main_search')
    }
    SK.core.enableDefaultValueFor(this.searchBox)
  }
}

//# SuckerFish
SK.enforceHover = function(selector){
  if ($.browser.msie) {
    $(selector).hover(
      function(){
        $(this).addClass('hover')
      },
      function(){
        $(this).removeClass('hover')
      }
    );
  }
}

//# SWF Upload
SK.swfupload = {
  multiMsg: 'You can upload multiple files at once.',
  flashFreeText: "\
    <p>\
      Having problems uploading? <a href=\"" + window.location.search + "&amp;no_flash=true\">Try our basic upload instead</a>.\
    </p>\
  ",
  init: function() {
        $('#main .content p').after('<p>'+SK.swfupload.multiMsg+' Max size: ' + SK.upload.settings().file_size_limit + '</p>' + SK.swfupload.flashFreeText)
  }
  
}

//# !setup
$(document).ready(function(){
  if ($.browser.msie && $.browser.version == 6.0) {
    SK.core.replacePNGWithGifForIE6();
  }
  
  $("body").addClass("js")
  
  if ($("body").find("#hide-announcement").length != 0) {
    $("#hide-announcement").bind("click", function(e){
      e.preventDefault();
      $.get($("#hide-announcement").attr("href"));
      $("#announcement").slideUp(600);
    })
  }
  
  // TODO: Move this somewhere out of the way
  $('.drop-down').hover(
    function(){ $(this).addClass("active"); },
    function(){ $(this).removeClass("active"); }
  );

  $($('.drop-down').find('a')).focus(
      function(){ $(this).parents('.drop-down').addClass("active"); }
    ).blur(
      function(){ $(this).parents('.drop-down').removeClass("active"); }
    );
  
  $('#new-quickshout').submit( 
    function () { $("#new-quickshout input[type=submit]")[0].disabled = true; } 
  );

  SK.enforceHover('.gigography .event');
  SK.enforceHover('#navigation li');
  
  if(!($('body').hasClass('sign-up'))) SK.searchSetup.init();
  SK.core.enableDefaultValueFor("input[name=lastfm_username]");
})


//# Ajax Feedback
SK.ajaxFeedback = {
  disableForm: function(form) {
    // if you don't want your form to be disabled while the ajax submits, give it class persistent
    if(!form.hasClass('persistent')) {
      $(form).find('select, input, textarea').attr('disabled','true')
    }
  },
  
  enableForm: function(form) {
    if(!form.hasClass('persistent')) {
      $(form).find('select, input, textarea').attr('disabled','false')
    }
  },
  
  pendRefreshingContent: function(target) {
    if($(target).hasClass('button')) {
      if($(target).parent('.ajax-pending-button').length == 0) { 
        pendingWrapper = $(document.createElement("span"))
                          .addClass("ajax-pending-button")
        $(target).wrap(pendingWrapper)
      } 
    } else {
      if ($(target).children('.ajax-pending').length == 0) {
        width = $(target).outerWidth();
        height = $(target).outerHeight();
        left = $(target).position().left;
        pendingMask = $(document.createElement("span"))
                      .addClass("ajax-pending")
                      .css({
                        position: 'absolute',
                        left: left,
                        top: $(target).position().top,
                        width: width,
                        height: height
                      })
        $(target).append(pendingMask)
      }
    }
  },

  // Accepts beforeSubmit params from jQuery.form plugin
  prepareForm: function(params,form,ajax) {
    SK.ajaxFeedback.disableForm(form)
    if($(form).hasClass('button-to')) {
      SK.ajaxFeedback.pendRefreshingContent($(form).children())
    } else {
      SK.ajaxFeedback.pendRefreshingContent(ajax.target)
    }
  },
  
  prepareSubmit: function(params, form, ajax) {
    submit = $(form).find("input.submit");
    if($(submit).parent('.ajax-pending-submit').length == 0) { 
      pendingWrapper = $(document.createElement("span")).addClass("ajax-pending-submit")
      pendingMask = $(document.createElement("span"))
                    .addClass("spinner")
                    .css({
                      position: 'absolute',
                      top: 0,
                      left: 0,
                      width: $(submit).outerWidth(),
                      height: $(submit).outerHeight()
                    })
      $(submit).wrap(pendingWrapper)
      $(submit).parent().append(pendingMask);
    } else {
      $(submit).parent().find("span.spinner").css("display", "block");    
    }
    
  },
  
  cleanSubmit: function(form) {
    submit = $(form).find("input.submit");
    $(submit).parent().find("span.spinner").css("display", "none");    
  }
  
}

//# Modailty
SK.modality = {
  identifiers: {
    modalPopupLink: 'a[rel*=modal]',
    modalPopupIframe: 'a[rel*=iframe-modal]',
    modalPopupForm: 'form[class*=modal]'
  },
  
  activateModal: function(e) {
    e.preventDefault();
    if ($(this).is("form")) {
      path = SK.core.ajaxifyResource($(this).attr("action") + "?" + $(this).serialize());
    } else {
      path = SK.core.ajaxifyResource($(this).attr("href"));
    }

    jQuery.facebox(function() {
      $.get(path, function(data) { $.facebox(data) })
    });

    return false;
  },
  
  initModalLinks: function(modal_links) {
    modal_links.livequery("click", SK.modality.activateModal);
  },

  initModalForms: function(modal_forms) {
    modal_forms.livequery("submit", SK.modality.activateModal);
  },
  
  init: function() {
    if (
      ($('body').hasClass('modal')) && 
      !($('body').hasClass('downloads')) &&
      !($('body').hasClass('feedback')) &&
      !($('body').hasClass('problems')) &&
      !($('body').hasClass('sign-up'))
      ) return;
    
    this.initModalLinks($(SK.modality.identifiers.modalPopupLink));
    this.initModalForms($(SK.modality.identifiers.modalPopupForm));
  }
  
}

//# !setup
$(document).ready(function(){
  SK.modality.init();
})

//# Date Pickers

//  Setup date-picker widgets on target date select node(s)
//  Will init all available nodes unless a specific identifier is specified
//  eg. SK.datePickers.init('#my-date-selector')

SK.datePickers = {
  // Default identifier used unless one is specified in the call
  identifier: '.datepicker',
  clonePair: false,//accepts an array; ['id of master date widget','id of the slave date widget']
  options: {
    appendText: 'mm/dd/yyyy',
    changeFirstDay: false,
		changeMonth: true,
		changeYear: true,
		constrainInput: false,
    showOn: 'button', 
    buttonImage: SK_ASSET_HOST + '/images/icons/calendar_add.png', 
    buttonImageOnly: true,
    yearRange: "1900:2020",
		onSelect: function(dateString,datePicker) { SK.datePickers.updateSelects(dateString, datePicker.input.parent()) }
  },
  
  init: function(clonePair, identifier) {
    if(identifier) this.identifier = identifier
    if(clonePair) this.clonePair = clonePair
    this.hideSelects()
    this.createDatePickerInput()
    $(this.identifier).parents('form').submit(function(){
        $('.date-picker-input').attr('disabled', 'disabled')
    })
  },
  
  hideSelects: function() {
    $(this.identifier).children().hide()
  },
  
  createDatePickerInput: function() {
    $(this.identifier).each(function(index, datePicker) {
      datePickerId = $(datePicker).attr('id')
      datePickerInput = $(document.createElement("input"))
                        .attr({
                          id: 'datepicker-'+datePickerId,
                          name: datePickerId+'[all]',
                          value: SK.datePickers.dateFromSelects(datePicker),
                          className: "text"
                        })
                        .addClass('date-picker-input')
                        .blur(function() { SK.datePickers.updateSelects($(this).val(), datePicker) })
      $(datePicker).append(datePickerInput)
      datePickerInput.datepicker(SK.datePickers.options)
      $('label[for="date[day]"]').attr("for","date[all]")
    })
  },
  
  dateFromSelects: function(datePicker) {
    if ($(datePicker).find('select[name*=day]').val() != -1) {
      selectedDate = $(datePicker).find('select[name*=month]').val()+'/'+
                     $(datePicker).find('select[name*=day]').val()+'/'+
                     $(datePicker).find('select[name*=year]').val()
      return selectedDate
    }
  },
  
  updateSelects: function(dateString, datePicker) {
    datePickerId = $(datePicker).attr('id')
    dateArray = dateString.split('/');
    
    $.each(dateArray, function(i,value){
      dateArray[i] = value * 1
    })
    
    if (dateArray[0] > 12) {
      var day = $('#'+datePickerId+'-day').find("option[value="+dateArray[0]+"]")
      var month = $('#'+datePickerId+'-month').find("option[value="+dateArray[1]+"]")
    } else {
      day = $('#'+datePickerId+'-day').find("option[value="+dateArray[1]+"]")
      month = $('#'+datePickerId+'-month').find("option[value="+dateArray[0]+"]")
    }
    var year = $('#'+datePickerId+'-year').find("option[value="+dateArray[2]+"]")

    if (day.attr("value") && month.attr("value") && year.attr("value")) {
      day.attr("selected", "selected");
      month.attr("selected", "selected");
      year.attr("selected", "selected");
      return true
    }
  }
}

SK.trackings = {
  identifiers: {
    objectTrackings: '.tracking-concerts, .tracking-following', 
    attendanceTrackings: '.tracking-im-going, .tracking-i-might-go',
    removeTrackerTrackings: '.tracking-concerts.delete, .tracking-following.delete'
  },
  
  startCallbacks: {},
  endCallbacks: {},
  
  setupTrackingButtons: function(elements) {
    $(elements).each(function(index, trackingButton){        
      $(trackingButton).wrap("<span></span>");
    });
    
    $(elements).livequery("submit", function(){
      SK.core.ajaxifyActionAttribute($(this), 'action')
      type = $(this).find("input.button").attr("form_class")
      
      $(this).ajaxSubmit({
        beforeSubmit: SK.ajaxFeedback.prepareForm,
        target: $(this).parents('.tracking')[0],
        success: function(){ SK.trackings.onSuccessfulTracking($(this), type) }
      });
      return false;
    });
  },
  
  onSuccessfulTracking: function(target, type) {
    button = $(target).find("."+type+" input.button");
    this.findPolarityOfTrackingAndPerformCallbackWith(button);

    //  this comment out because it appears to work without it and is causing issues in IE

    // if ($(target).parents(".my-attendance.upcoming").length > 0) {
    //   parent = $(target).parents(".my-attendance.upcoming")[0]
    //   $(parent).children().find("input.button").not(button).removeClass("selected")
    //    $(parent).children().find("input.button").not(button).css("border", "1px solid red")
    // }
  },
  
  findPolarityOfTrackingAndPerformCallbackWith: function(button) {
    if ($(button).hasClass("selected")) {
      this.performCallBackFor(SK.trackings.startCallbacks, button);
      SK.trackings.afterStartTracking();
    } else {
      this.performCallBackFor(SK.trackings.endCallbacks, button);
      SK.trackings.afterEndTracking();
    }
  },
  
  performCallBackFor: function(hash, button) {
    for (key in hash) {
      if ($(button).parents(key).length > 0) {
        hash[key].call(hash,button)
        return
      }
    }
  },
    
  registerCallback: function(options) {
    hash = options.type
    hash[options.selector] = options.callback
  },
  
  //helper methods
  
  forceTrackingFormToTrackedState: function(form) {
    $(form).attr('action', $(form).attr('action').replace(/\/trackings/, '/trackings/untrack'))
    $(form).children().find("input").addClass("selected");
  },
  
  forceTrackingFormToUntrackedState: function(form) {
    $(form).attr('action', $(form).attr('action').replace(/trackings\/untrack/, 'trackings'))
    $(form).children().find("input").removeClass("selected");
  },
  
  //overwrite these elsewhere
  
  afterStartTracking: function() {},
  afterEndTracking: function() {},
  
  init: function() {
    if ($("body").hasClass("tracker")) {
      this.initRemoveTrackerTrackings();  
    } else {
      this.setupTrackingButtons(this.identifiers.objectTrackings);
      this.setupTrackingButtons(this.identifiers.attendanceTrackings); 
    }
  },
  
  // these should be in tracker.js
  initRemoveTrackerTrackings: function() {
    if (!$("body").hasClass("tracker")) return;    
    
    $(this.identifiers.removeTrackerTrackings).each(function(index, removeButton) {
      $(removeButton).wrap("<span></span>")
    });
    
    $(this.identifiers.removeTrackerTrackings).livequery("submit", function(){
      SK.core.ajaxifyActionAttribute($(this), 'action')
      form = $(this)
      $(this).ajaxSubmit({
        beforeSubmit: SK.ajaxFeedback.prepareForm,
        success: function(){ SK.trackings.removeTrackedObject(form)}
      });
      return false;
    })
    
  },
  
  removeTrackedObject: function(form) {
    $(form).parents('li.tracked-object').slideUp(400, function() { 
      $(this).remove(); 
      $('#tracked-objects li.tracked-object').each(function(i, li) {
        $(li).removeClass("alternate");
        if ((i % 2) == 0 ) $(li).addClass("alternate");
      });
    });
    $(form).remove();
  }
  
}



$(document).ready(function(){
  if ($("body").hasClass("not-logged-in")) return;
  if ($("body").hasClass("tracker.modal")) return;
  SK.trackings.init();
});

SK.problems = {
  otherHeight: false,
  
  identifiers: {
    main: '.problems:first',
    mainWrap: '.problems .content form',
    listWrap: '#problem-wrap',
    dataDrilldown: '#data-drilldown',
    dataMenu: '#data-menu',
    editHint: '#data-menu .hint',
    problemOptions: '.option',
    headingsAndOptions: 'div.problem, div.option',
    problemForm: '#problem-form',
    formWraps: '.form-wrap'
  },
  
  errors: new Array(),
  
  setupErrors: function() {
    this.errors["captchaError"] = "#captcha";
    this.errors["emailError"] = "#emailField";
    this.errors["blankError"] = "#messageField";
  },
  
  rewriteDom: function() {
    submenu = $(this.identifiers.dataMenu)
    $(submenu).css('left', 510);
    $(this.identifiers.mainWrap).prepend(submenu);
  },
  
  setupDrillDown: function() {
    $(this.identifiers.dataDrilldown).bind("click", function(){
      SK.problems.viewState.data();
    })
  },
  
  setupOptions: function() {
    $(this.identifiers.problemOptions).each(function(i, option){
      $(option).bind("click", function(){
        $(option).find("input[type='radio']").attr("checked", "true")
        if($(option).hasClass("selected")) return;
        SK.problems.viewState.selected(option);
      })
    })
  },
  
  setupReturnAndCancelLink: function() {
    $("#back-link").bind("click", this.viewState.start)
    $("#cancel-link").bind("click", this.viewState.previous)
  },
  
  setupSubmission: function() {
    $(this.identifiers.mainWrap).livequery("submit", function(){
      SK.core.ajaxifyActionAttribute($(this), 'action');
       
      $(this).ajaxSubmit({
        beforeSubmit: SK.ajaxFeedback.prepareSubmit,
        success: SK.problems.handleAjaxSubmit,
        dataType: "json"
      });
      return false
    })
  },
  
  handleAjaxSubmit: function(data, status) {
    SK.problems.removeErrors();
    
    if (data.status == "ok") {
      SK.problems.handleSubmitSuccess(data.body);
    } else {
      SK.ajaxFeedback.cleanSubmit($(SK.problems.identifiers.mainWrap));
      SK.problems.handleSubmitError(data.body);
    }
    
  },
  
  handleSubmitError: function(messages) {
    SK.problems.activeErrors = [];

    $(messages).each(function(i, msg){
      SK.problems.activeErrors.push($(SK.problems.errors[msg["errorType"]]));
      $(SK.problems.errors[msg["errorType"]]).addClass("error")
      msgE = $(document.createElement("span")).addClass("error-message").text(msg["message"])
      $(SK.problems.errors[msg["errorType"]]).prepend(msgE)
    })
    
    $(SK.problems.identifiers.mainWrap).css("height", $(SK.problems.identifiers.mainWrap).height() + 40);
    Recaptcha.reload();
  },
  
  handleSubmitSuccess: function(body) {
    $(SK.problems.identifiers.main).replaceWith(body);
    
    closeel = $("<input type='submit' class='button' value='Close'></input>")
              .bind("click", function(){
                jQuery(document).trigger('close.facebox');
              })
              
    $(".problems .content .thanks").append(closeel);
  },
  
  removeErrors: function() {
    $(SK.problems.activeErrors).each(function(i, error){
      $(error).removeClass("error");
      $(error).find("span.error-message").remove();
    });
  },
  
  resetForm: function() {
    $(this.identifiers.mainWrap)[0].reset();
  },
  
  viewState: {
    current: "start",
    
    previous: function() {
      if (SK.problems.viewState.current == "start") {
        SK.problems.viewState.start()
      } else {
        SK.problems.viewState.data()
      }
      return false
    },
    
    start: function() {
      SK.problems.viewState.current = "start";
      SK.problems.removeErrors();
      SK.problems.resetForm();
      SK.problems.deSelectAllOptions();
      SK.problems.resizeToOriginal();
      SK.problems.closeDataMenu();
    },
    
    data: function() {
      SK.problems.viewState.current = "data";
      SK.problems.removeErrors();
      SK.problems.resetForm();
      SK.problems.deSelectAllOptions();
      SK.problems.openDataMenu();
      SK.problems.introduceHint();
      SK.problems.resizeToData();
    },
    
    selected: function(option) {
      SK.problems.removeErrors();
      SK.problems.resetForm();
      SK.problems.removeHint();
      SK.problems.deSelectAllOptions();
      SK.problems.makeOptionSelected(option); 
      SK.problems.showFormForOption(option);
      SK.problems.resizeViewForOption(option);
    }
   },
   
   toggleDataMenu: function() {
     $menu = $(this.identifiers.dataMenu);
     $menu.animate({ left: parseInt($menu.css('left'),10) == 0 ? 510 : 0 }, {duration:500, easing:"easeOutCubic"});
   },
   
   closeDataMenu: function() {
     $menu = $(this.identifiers.dataMenu);
     $menu.animate({ left: 510}, {duration:500, easing:"easeOutCubic"});     
   },
   
   openDataMenu: function() {
     $menu = $(this.identifiers.dataMenu);
     $menu.animate({ left: 0 }, {duration:500, easing:"easeOutCubic"});     
   },
   
   introduceHint: function() {
     if ($.browser.msie) return $(this.identifiers.editHint).show();

     $hint = $(this.identifiers.editHint);
     $hint.css("opacity", 0);
     setTimeout(function(){
       $hint.fadeTo(600, 1);
     }, 400)
     
   },
   
   removeHint: function() {
     if ($.browser.msie) return $(this.identifiers.editHint).hide();
     $(this.identifiers.editHint).fadeTo(300, 0);
   },
   
   makeOptionSelected: function(option) {
     $(option).addClass("selected");
   },
   
   deSelectAllOptions: function() {
     $(this.identifiers.problemForm).css("display", "none");
     $(this.identifiers.problemOptions).removeClass("selected");
   },
   
   showFormForOption: function(option) {
     $(this.identifiers.formWraps).show();
     $(option).children(".form-wrap").append($(this.identifiers.problemForm));
     $(this.identifiers.problemForm).css("display", "block");
   },
   
   resizeViewForOption: function(option) {
     var height;
     if($(option).parents("#data-menu").length == 1) {
       height = $(this.identifiers.dataMenu).height();
     } else {
       if(this.otherHeight == false) {
         $(this.identifiers.mainWrap).css("height", "auto");
         this.otherHeight = $(this.identifiers.mainWrap).height();
       } 
       height = this.otherHeight;
     }
     $(this.identifiers.mainWrap).animate({height: height}, {duration:500, easing:"easeOutCubic"});
   },
   
   resizeToOriginal: function() {
     $(this.identifiers.mainWrap).animate({height: this.originalHeight}, {duration:500, easing:"easeOutCubic"});
   },
   
   resizeToData: function() {
     $(this.identifiers.mainWrap).animate({height: $(this.identifiers.dataMenu).height() }, {duration:500, easing:"easeOutCubic"});
   },
  
  init: function(){
    this.setupErrors();
    this.rewriteDom();
    this.setupDrillDown();
    this.setupOptions();
    this.setupReturnAndCancelLink();
    this.setupSubmission();

    setTimeout(function(){
      SK.problems.originalHeight = parseInt($(SK.problems.identifiers.listWrap).height(),10);
    },500)
  }
  
}

SK.Share = {
  strings: {
    im_going:     "Woohoo! Tell your friends.",
    i_might_go:   "Tell your friends you might go to this.",
    i_was_there:  "Was it amazing? Tell your friends about it."
  },
  
  // usage is like so:
  // revealShare({
  //   tracking_type: "im-going",
  //   ga_reveal: "big ugly google path",
  //   ga_click: {
  //     fb: "big ugly google path",
  //     twitter: "big ugly google path"
  //   },
  //   launch_urls: {
  //     fb: "somewhere on facebook",
  //     twitter: {
  //       im_going: "somewhere on twitter",
  //       i_might_go: "somewhere on twitter",
  //       i_was_there: "somewhere on twitter",
  //     }
  //   },
  //   user_has_twitter: true,
  //   user_twitter_settings_path: "a path"
  // })
  
  revealShare: function(options) {
    
    tracking_type = options["tracking_type"];
    ga_reveal     = options["ga_reveal"];
    ga_click      = options["ga_click"];
    fb_launch_url = options["launch_urls"]["fb"];
    twit_launchs  = options["launch_urls"]["twitter"];

    user_has_twitter = options["user_has_twitter"];
    user_twitter_settings_path = options["user_twitter_settings_path"];
    
    var promptText = "";
    var twit_launch_url = ""
    
    switch(tracking_type) {
      case "im-going":
        promptText = SK.Share.strings.im_going;
        twit_launch_url = twit_launchs["im_going"];
      break;
      case "i-might-go":
        promptText = SK.Share.strings.i_might_go;
        twit_launch_url = twit_launchs["i_might_go"];
      break;
      case "i-was-there":
        promptText = SK.Share.strings.i_was_there;
        twit_launch_url = twit_launchs["i_was_there"];
      break;
    }
    
    wrap = $("<div id='share-socially-reveal'></div>")
            .append($("<span class='label'></span>").text(promptText))
            .append($("<span class='fb_share_button'>Share</span>\n").bind("click", function() {
              pageTracker._trackPageview(ga_click["fb"]);
              SK.Share.launchFBSharePopUp(fb_launch_url);
            }))            
            .append(SK.Share.getTwitterButtonOrMessage(user_has_twitter, 
                                                          ga_click["twitter"], 
                                                          twit_launch_url, 
                                                          user_twitter_settings_path))

    
    $("#title-bar").append(wrap)
    $("#share-socially-reveal").css("width", $("#share-socially-reveal").width() + 1);
    $("#share-socially-reveal").hide().slideDown("slow");
      
    pageTracker._trackPageview(ga_reveal);
  },
  
  getTwitterButtonOrMessage: function(user_has_twitter, ga_click, launch, user_twitter_settings_path) {
   msg =  user_has_twitter ? (
     $("<a href='#' class='twitter_connected_message'>You're connected</a>").bind("click", function() {
       window.location = user_twitter_settings_path
       return false;
     })
    ) : (
      $("<span class='twitter_share_button'>Share</span>").bind("click", function() {
        pageTracker._trackPageview(ga_click);
        SK.Share.launchTwitterSharePopUp(launch);
      })
    )
    
    return msg
  },
  
  launchFBSharePopUp: function(shareUrl) {
    window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(shareUrl),'sharer','toolbar=0,status=0,width=626,height=436');
    return false;
  },
  
  launchTwitterSharePopUp: function(shareUrl) {
    window.open(shareUrl);
    return false;
  },
  
  convertTrackingPathWithButtonLabel: function(button, path) {
	  label = SK.Share.convertButtonToTrackingType(button)
		track = path.replace("button_label",label);
		
		return track
  },
  
  convertButtonToTrackingType: function(button) {
    return $(button).attr("value").replace(/\s/g, "-").replace("'", "").toLowerCase();
  },

  init: function() {
    $("a[rel='facebook']").bind("click", function(e){
      uri = $(this).attr("href");
      share_uri = uri.substring(uri.search("\\?")+3, uri.length)
      SK.Share.launchSharePopUp(share_uri);
      return false;
    });
  }
};

$(document).ready(function(){
  SK.Share.init();
});

SK.signup = {
  changeBtnSel:       '#change_location_button',
  formSel:            'form.metro_search',
  searchFormWrapSel:  '#location_search_form_wrap',
  initialInfoSel:     '#new_user_location > span.info',
  ajaxStateLink:      "#ajaxStateLink",
  searchField:        "#location_lookup", 
  searchSubmit:       "#search_submit_btn",
  ajaxCommitParam:    "#ajaxCommitParam",
  resultsWrapSel:     "#search_results_wrap",
  resultsListSel:     "#place-listing", 
  topMatchSel:        "ul li.first-choice",
  selectedMetroLabel: "#selected_metro_name",
  indicator:          "#search_location_ajax", 
  
  reWriteChangeButton: function() {
    if ($('#ajaxStateLink').length > 0) return;

    var hidden = $("<input id=\"ajaxCommitParam\" type=\"hidden\" name=\"commit\" value=\"change\"></input>")
    $(SK.signup.formSel).append(hidden)

    var changeLink = $("<a id=\"ajaxStateLink\">change</a>").attr('href', '#').bind("click", this.handleChange)
    $(this.changeBtnSel).remove()
    $("#changewrap span").css("display", "inline").append(changeLink)
  },
  
  liveWireSearchField: function() {
    $(this.searchField).keydown(function(e){
      if ($(SK.signup.searchField).attr("value").length < 2) {
        $(SK.signup.indicator).hide()
        if (SK.signup.timeout) clearTimeout(SK.signup.timeout);
        if (e.keyCode == 13) e.preventDefault();
        return;
      } 
      
      form = $(SK.signup.formSel)
      SK.core.ajaxifyActionAttribute(form, 'action')

      if (SK.signup.timeout) clearTimeout(SK.signup.timeout);
      switch(e.keyCode) {
        case 16:
        case 17:
        case 18:
        case 91:
        case 32:
        case 93:
        case 37:
        case 40:
        case 39:
        case 38:
        case 8:
        case 27:
          if (SK.signup.timeout) clearTimeout(SK.signup.timeout);
          break;
        case 13:
          e.preventDefault();
        case 9:
          if (SK.signup.timeout) clearTimeout(SK.signup.timeout);
          SK.signup.handleSearch();
          break;
        default:
          $(SK.signup.indicator).show()
          SK.signup.timeout = setTimeout(SK.signup.handleSearch, 2000)
          break;
      }
    })
  },
  
  activateResultsList: function() {
    $(SK.signup.resultsListSel+" li").each(function(i,li){
      $(li).bind("click", function(){SK.signup.handleListSelect(li)})
    })
  },
  
  resetFormAction: function() {
    form = $(SK.signup.formSel)
    SK.core.deAjaxifyActionAttribute(form, 'action')
  },
  
  handleListSelect: function(li){
    SK.signup.onEndSearch();
    $(SK.signup.resultsListSel+" li").attr("class", "")
    $(li).attr("class", "first-choice")
    SK.signup.viewState.result.helpers.setSelectedLocation(li);
    $(SK.signup.resultsListSel).slideUp(600);
    setTimeout(SK.signup.viewState.show, 700);
  },
   
  handleSearch: function() {
    $("#hiddenSelectedMetro").remove();
    $(SK.signup.formSel).ajaxSubmit({
      target: $(SK.signup.resultsWrapSel),
      success: SK.signup.viewState.results
    });
  },
  
  handleChange: function(e) {
    e.preventDefault();
    
    $(SK.signup.ajaxCommitParam).attr("value", "change");
    
    form = $(SK.signup.formSel)
    SK.core.ajaxifyActionAttribute(form, 'action')
    form.ajaxSubmit({
      target: $(SK.signup.searchFormWrapSel),
      success: SK.signup.viewState.search
    });
  },
  
  handleCancel: function(e) {
    e.preventDefault();
    SK.signup.viewState.show();
    SK.signup.onCancelSearch();
  },
  
  handleReveal: function(e) {
    if (e) e.preventDefault();
    $(SK.signup.resultsWrapSel+" .info").html(SK.signup.originalInfo)
    $(SK.signup.resultsListSel).slideDown(600);
    SK.signup.activateResultsList();
  },
  
  viewState: {
    search: function() {
      SK.signup.onBeginSearch();
      $(SK.signup.indicator).hide()
      $(SK.signup.initialInfoSel).css("display", "none")
      $(SK.signup.ajaxStateLink).text("cancel")
      $(SK.signup.ajaxStateLink).unbind("click", SK.signup.handleChange)
      $(SK.signup.ajaxStateLink).bind("click", SK.signup.handleCancel)
      $(SK.signup.ajaxCommitParam).attr("value", "Search");
      
      SK.signup.liveWireSearchField();
      SK.signup.resetFormAction();
    },
    
    show: function() {
      $(SK.signup.selectedMetroLabel).css("color", "#000")
      $(SK.signup.indicator).hide()
      $(SK.signup.searchFormWrapSel).empty();
      $(SK.signup.initialInfoSel).css("display", "block");
      $(SK.signup.ajaxStateLink).text("change")
      $(SK.signup.ajaxStateLink).unbind("click", SK.signup.handleCancel)
      $(SK.signup.ajaxStateLink).bind("click", SK.signup.handleChange)
      $(SK.signup.ajaxCommitParam).attr("value", "change");
      
      SK.signup.resetFormAction();
    },
    
    results: function() {
      $(SK.signup.indicator).hide()
      $(SK.signup.searchField).blur();
      results = $(SK.signup.resultsListSel+" li").length
      
      if (results == 0) {
        SK.signup.viewState.result.none();
        SK.signup.onEndSearch(true);
      } else if (results == 1) {
        SK.signup.viewState.result.certain();
        SK.signup.onEndSearch();
      } else if (results > 1 && results < 11) {
        SK.signup.viewState.result.ambiguous();
        SK.signup.onEndSearch();
      } else {
        SK.signup.viewState.result.clueless();
      }
      
    },
    
    result: {
      helpers: {
        clearSelectedLocation: function(ele) {
          $(ele).attr("class", "")
          $(ele).children("input:radio").attr('checked', false)
        },
        
        setSelectedLocation: function(ele) {
          this.setCurrentLocationText($(ele).children("label").text())
          this.setSelectedLocationHiddenField($(ele).children("input").attr("value"))
        },
        
        setCurrentLocationText: function(text){
          $(SK.signup.selectedMetroLabel).css("color", "#000")
          $(SK.signup.selectedMetroLabel).text(text)
        },
        
        setSelectedLocationHiddenField: function(value) {
          $("#hiddenSelectedMetro").remove();
          $(SK.signup.formSel).append(
            $("<input id=\"hiddenSelectedMetro\" type=\"hidden\" name=\"metro_area_id\" value=\""+value+"\"></input>")
          );
          
        }
      },
      
      certain: function(){
        this.helpers.setSelectedLocation($(SK.signup.topMatchSel))
        SK.signup.viewState.show();
      },
      
      ambiguous: function(){
        this.helpers.setSelectedLocation($(SK.signup.topMatchSel))
        
        reveal = $("<a href=\"#\">See them now</a>").bind("click", SK.signup.handleReveal)
        SK.signup.originalInfo = $(SK.signup.resultsWrapSel+" .info").html()
        $(SK.signup.resultsWrapSel+" .info").append(" ").append(reveal);

        SK.signup.resetFormAction();
        $(SK.signup.searchField).remove();
        $(SK.signup.ajaxStateLink).text("change")
        $(SK.signup.ajaxStateLink).bind("click", SK.signup.handleChange)
        $(SK.signup.ajaxStateLink).unbind("click", SK.signup.handleCancel)
      },
      
      clueless: function(){
        this.helpers.clearSelectedLocation($(SK.signup.topMatchSel))
        SK.signup.originalInfo = $(SK.signup.resultsWrapSel+" .info").html()
        $(SK.signup.selectedMetroLabel).css("color", "#959292")
        
        $(SK.signup.formSel).blur();
        if (SK.signup.timeout) clearTimeout(SK.signup.timeout);
        SK.signup.handleReveal();
        
      },
      
      none: function(){
        if (SK.signup.timeout) clearTimeout(SK.signup.timeout);
        SK.signup.resetFormAction();
      }
    }
    
  },
  
  //overwrite these elsewhere
  
  onBeginSearch: function() {},
  onEndSearch: function(failed) {},
  onCancelSearch: function() {},
  
  init: function() {
    this.reWriteChangeButton();
  }
}

$(document).ready(function(){
  SK.signup.init();  
});




