/**
 * Discovery Place common js file
 *
 * Includes common Discovery Place functions and jQuery bindings
 *
 * Also includes the following plug-ins:
 *  - Cookie plugin
 *  - ScrollTo
 *  - Innerfade
 *	- Masked Input
 *
 */



$(document).ready(function(){
	
	// png fix
	// fix ie6
	var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
	if (badBrowser) {
		// png fix
		$('img[src$=.png]').each(function() {
			if (!this.complete) {
				this.onload = function() { fixPng(this) };
			} else {
				fixPng(this);
			}
		});
		// cache bg images
		try {
			document.execCommand("BackgroundImageCache", false, true);
		  } catch(err) {}
	}

	
	// alert ticker animation
	$('#alert').innerfade({ 
		animationtype: 'fade', 
		speed: 'slow', 
		timeout: '6000', 
		type: 'sequence', 
		containerheight: '26',
		runningclass: 'innerfade',
		children: 'span'
	}); 
	
	
	// alert close link functionality
	$('#alert_wrap a.link_close').click(function(){
		// hide alert box all fancy-like
		$('#alert_wrap').slideToggle('slow', function(){$(this).remove()});
		// set cookie to not show alert for 1 day	
		$.cookie('dp_alert', 'no', { expires: 1, path: '/' }); // set cookie with an expiration date 1 day in the future
		
		// set cookie for when user closed alert box (used to check if new alerts added after closing - if so alerts will show again even before cookie expires)
		var today = new Date();
		var cur_month = '0' + (today.getMonth()+1);
		cur_month = cur_month.slice(-2, cur_month.length);
		var cur_date = '0' + today.getDate();
		cur_date = cur_date.slice(-2, cur_date.length);
		var closed = today.getFullYear() + '-' + cur_month + '-' + cur_date + '_' + today.getHours() + '-' + today.getMinutes() + '-' + today.getSeconds();
		$.cookie('dp_alert_closed', closed, { expires: 1, path: '/' }); 
		
		return false;
	});
	
	
	// blog month selector
	$('.post_month_search select').change(function(){
		var month_year = $(this).val().split('/');
		window.location = '/blog/date/'+month_year[0]+'/'+month_year[1]+'/';
	});

	
	// get rid of trailing borders on certain lists
	$('.list_inset li:last-child, .listing .list_item:last-child').addClass('last');
	
	
	// get rid of superfluous spacing on some p's
	$('li p:last-child, .list_item p:last-child').addClass('last');
	
	
	// focus/blur text box value
	$('input[type=text], textarea').focus(function(){
		if ($(this).val() == $(this).attr('title')) {
			$(this).val('');
		}
		$(this).addClass('input_focus');
	}).blur(function(){
		if ($(this).val() == '') {
			$(this).val($(this).attr('title'));
		}
		$(this).removeClass('input_focus');
	})
	$('select').focus(function(){
		$(this).parents('div.skinned-select').addClass('input_focus');
	}).blur(function(){
		$(this).parents('div.skinned-select').removeClass('input_focus');
	})
	
	
	// expander
	$('.expander dt').click(function(){
		$(this).parents('dl').children('dd').slideToggle();
		$(this).toggleClass('open');
	});
	
	
	// scroller
	$('a.scroller').click(function(){
		var scroll_target = $(this).attr("href");
		$.scrollTo($(scroll_target), 800);
		return false;
	});
	

	if (!badBrowser) {	
		// jQuery skinning html select boxes (http://www.lotsofcode.com/javascript-and-ajax/jquery-select-box-skin.htm)
		$('.dp_select').each(function(i) {
			selectContainer = $(this);
			// Remove the class for non JS browsers
			selectContainer.removeClass('dp_select');
			// Add the class for JS Browers
			selectContainer.addClass('skinned-select');
			// Find the select box
			selectContainer.children().before('<div class="select-text">a</div>').each(function() {
				$(this).prev().text(this.options[this.selectedIndex].innerHTML);
			});
			// Store the parent object
			var parentTextObj = selectContainer.children().prev();
			// As we click on the options
			selectContainer.children().click(function() {
				// Set the value of the html
				parentTextObj.html(this.options[this.selectedIndex].innerHTML);
			}).keyup(function() {
				// Set the value of the html
				parentTextObj.html(this.options[this.selectedIndex].innerHTML);
			});
		});	
	}
	
	
	// control Other Amount box on donation form
	$('#f_donate_amount').change(function() {
		if ($(this).val() == 'other') {
			$('#f_donation_other_wrap .input').hide().removeClass('hidden').fadeIn();
			$('#f_donation_other_wrap :input:first').focus();
		} else {
			$('#f_donation_other_wrap .input').hide();
		}
	});
	
	
	// Colorbox triggers
	$("a.cbox_photo").colorbox({transition:"elastic"});
	$("a.cbox_video").colorbox({href:$(this).attr("href"), width: "60%", height: "60%", iframe:true});
	
	
	// Toggle	
	$(".toggler").click(function(){
		obj = $(this).attr("rel");
		$('#'+obj).slideToggle("fast", function() { adjustHero(); });
		return false;
	});	
	
	
	// anchor ID: form_button submits form contained in
	$("#form_button").click(function()
	{
		if ($("#f_form_check").length > 0)
		{
			$("#f_form_check").val("okay");
		}
		
		$(this).parents("form").submit();
		$(this).hide("fast");
		$(this).siblings("#form_loading").show("fast");
	});
	
	
	// Add error class to all inputs if form_errors input exists and has contents
	// -- form_errors input is a JSON string built in the form processing controller and passed to the view
	if ($("form :input[name=form_errors]").length > 0)
	{
		var errors = $("form :t[name=form_errors]").val();
		if (errors.length > 0) {
			var data = eval('(' + errors + ')');
	
			$("input").removeClass('error');
			$("textarea").removeClass('error');
			for (i=0; i<data.errors.length; i++) {
				$("#"+data.errors[i].input).parents(".input, .normal").find("label, :input, .skinned-select").addClass('error');
			}
		}
	}
	
	
	// Set up masks based on class names
	$.mask.definitions['~']='[0-9]?';
	$(".date_mask").each(function(){ $(this).mask("99/99/9999"); });
	$(".exp_mask").each(function(){ $(this).mask("99/99"); });
	$(".phone_mask").each(function(){ $(this).mask("999.999.9999"); });
	$(".zip_mask").each(function(){ $(this).mask("99999"); });
	$(".cc_mask").each(function(){ $(this).mask("9999-9999-9999-999?9"); });
	$(".ccv_mask").each(function(){ $(this).mask("999?9"); });
	
	
	// Fix fixed background hgome page flash hero
	$(window).scroll(function() {
		adjustHero("false");
	});
	$(window).resize(function() {
		adjustHero("false");
	});
});





function adjustHero() {
	if ($('#home_feature_player').length > 0) {
		var newsletter = ($('#newsletter_wrap').is(':hidden')) ? "false" : "true";
		document.home_feature_player.adjustBG($(window).width(), $(window).scrollTop(), newsletter);
	}
}







// cufon font replacement
Cufon.replace('#sub_nav a.sub_link', { fontFamily: 'Futura-Cond', hover: true });
Cufon.replace('h1.alt_h1, h2:not(.alt_h2_2), h3, #sub_nav .title', { fontFamily: 'Futura-Cond' });
Cufon.replace('h2.alt_h2_2', { fontFamily: 'Futura-CondExtBol' });
Cufon.CSS.ready(function() {
	// everything's been rendered now
	$('#sub_nav a.sub_link').fadeIn();
	$('#sub_nav .title').fadeIn();
}); 
// end cufon replacement








// png fix info
var blank = new Image();
blank.src = '/assets/images/clear.gif';

function fixPng(png) {
	var src = png.src;
	if (!png.style.width) { png.style.width = $(png).width(); }
	if (!png.style.height) { png.style.height = $(png).height(); }
	png.onload = function() { };
	png.src = blank.src;
	png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
}
// end png fix





// get directions from Google maps
function get_directions(){
	from_addr = $("#getting_here #f_from_address").val();
	if(from_addr == ""){
		$("#getting_here #f_from_address").val("Please enter an address...");
	} else {
		from_addr = from_addr.replace(" ","+");
		window.open("http://maps.google.com/maps?f=d&saddr=" + from_addr + "&daddr=1658+Sterling+Road,+Charlotte,+NC+28209&hl=en&geocode=&mra=ls&sll=35.2208,-80.853555&sspn=0.031378,0.043688&ie=UTF8&z=");
	}
}





// form submission function
function submit_form() {
	$("#form_button").hide();
	$("#form_loading").show();
	// get action to assign processing url
	switch($('#comment_form :input[name=action]').val()) {
		case 'blog':
			var url_path = "/blog/post_comment/";
			break;
		case 'contact':
			var url_path = "/about/contact/submit/";
			break;
	}
	$.ajax({
		type: "POST", 
		url: url_path, 
		data: $("#comment_form").serialize(),
		dataType: "json", 
		success: function (data, textStatus) {
			if (data.errors) {
				$("#form_msg_success").slideUp("fast");
				$("#form_msg_error").slideDown("fast");
				$("#form_button").show();
				$("#form_loading").hide();
				$("input").removeClass('error');
				$("textarea").removeClass('error');
				for (i=0; i<data.errors.length; i++) {
					if (data.errors[i].display.length > 0) {
						$("#"+data.errors[i].input).addClass('error');
					}
				}
				return false;
			} else {
				$("#comment_form")[0].reset();
				$("input").removeClass('error');
				$("textarea").removeClass('error');
				$("#form_msg_success").slideDown("fast");
				$("#form_msg_error").slideUp("fast");
				$("#form_button").show();
				$("#form_loading").hide();
				
				// output new comment if making comment on blog
				switch($('#comment_form :input[name=action]').val()) {
					case 'blog':
						$("#comments .comments_listing").prepend(data.html);
						$("#comments .comments_listing .comment.hidden").slideDown("fast");
						var old_comment_count = $(".comment_summary .comment_count").text();
						$(".comment_summary .comment_count").text(parseInt(old_comment_count)+1);
						if (data.social == "TRUE") {
							update_facebook_user();
						}
						break;
				}
				return true;
			}
		}
	});
}
// end form submission





// join newsletter function
function join_newsletter() {
	$("#jn_form_button").hide();
	$.ajax({
		type: "POST", 
		url: "/assets/helpers/jquery.form.php", 
		data: $("#newsletter_form").serialize(),
		dataType: "json", 
		success: function (data, textStatus) {
			if (data.errors) {
				$("#jn_form_button").show();
				$("input").removeClass('error');
				for (i=0; i<data.errors.length; i++) {
					if (data.errors[i].display.length > 0) {
						$("#"+data.errors[i].input).addClass('error');
					}
				}
				return false;
			} else {
				document.newsletter_form.reset();
				$("#newsletter_form_container").html('<p>Thank you for joining!</p>');
				window.setTimeout(function() {
					$('#newsletter_wrap').slideUp();
				}, 4000);
				return true;
			}
		}
	});
}
// end join newsletter




/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
// end cookie plugin





/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;
(function(d) {
    var k = d.scrollTo = function(a, i, e) {
        d(window).scrollTo(a, i, e)
    };
    k.defaults = {
        axis: 'xy',
        duration: parseFloat(d.fn.jquery) >= 1.3 ? 0 : 1
    };
    k.window = function(a) {
        return d(window)._scrollable()
    };
    d.fn._scrollable = function() {
        return this.map(function() {
            var a = this,
            i = !a.nodeName || d.inArray(a.nodeName.toLowerCase(), ['iframe', '#document', 'html', 'body']) != -1;
            if (!i) return a;
            var e = (a.contentWindow || a).document || a.ownerDocument || a;
            return d.browser.safari || e.compatMode == 'BackCompat' ? e.body: e.documentElement
        })
    };
    d.fn.scrollTo = function(n, j, b) {
        if (typeof j == 'object') {
            b = j;
            j = 0
        }
        if (typeof b == 'function') b = {
            onAfter: b
        };
        if (n == 'max') n = 9e9;
        b = d.extend({},
        k.defaults, b);
        j = j || b.speed || b.duration;
        b.queue = b.queue && b.axis.length > 1;
        if (b.queue) j /= 2;
        b.offset = p(b.offset);
        b.over = p(b.over);
        return this._scrollable().each(function() {
            var q = this,
            r = d(q),
            f = n,
            s,
            g = {},
            u = r.is('html,body');
            switch (typeof f) {
            case 'number':
            case 'string':
                if (/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)) {
                    f = p(f);
                    break
                }
                f = d(f, this);
            case 'object':
                if (f.is || f.style) s = (f = d(f)).offset()
            }
            d.each(b.axis.split(''), function(a, i) {
                var e = i == 'x' ? 'Left': 'Top',
                h = e.toLowerCase(),
                c = 'scroll' + e,
                l = q[c],
                m = k.max(q, i);
                if (s) {
                    g[c] = s[h] + (u ? 0 : l - r.offset()[h]);
                    if (b.margin) {
                        g[c] -= parseInt(f.css('margin' + e)) || 0;
                        g[c] -= parseInt(f.css('border' + e + 'Width')) || 0
                    }
                    g[c] += b.offset[h] || 0;
                    if (b.over[h]) g[c] += f[i == 'x' ? 'width': 'height']() * b.over[h]
                } else {
                    var o = f[h];
                    g[c] = o.slice && o.slice( - 1) == '%' ? parseFloat(o) / 100 * m: o
                }
                if (/^\d+$/.test(g[c])) g[c] = g[c] <= 0 ? 0 : Math.min(g[c], m);
                if (!a && b.queue) {
                    if (l != g[c]) t(b.onAfterFirst);
                    delete g[c]
                }
            });
            t(b.onAfter);
            function t(a) {
                r.animate(g, j, b.easing, a &&
                function() {
                    a.call(this, n, b)
                })
            }
        }).end()
    };
    k.max = function(a, i) {
        var e = i == 'x' ? 'Width': 'Height',
        h = 'scroll' + e;
        if (!d(a).is('html,body')) return a[h] - d(a)[e.toLowerCase()]();
        var c = 'client' + e,
        l = a.ownerDocument.documentElement,
        m = a.ownerDocument.body;
        return Math.max(l[h], m[h]) - Math.min(l[c], m[c])
    };
    function p(a) {
        return typeof a == 'object' ? a: {
            top: a,
            left: a
        }
    }
})(jQuery);





/* =========================================================

// jquery.innerfade.js

// Datum: 2008-02-14
// Firma: Medienfreunde Hofmann & Baldes GbR
// Author: Torsten Baldes
// Mail: t.baldes@medienfreunde.com
// Web: http://medienfreunde.com

// based on the work of Matt Oakes http://portfolio.gizone.co.uk/applications/slideshow/
// and Ralf S. Engelschall http://trainofthoughts.org/

 *
 *  <ul id="news"> 
 *      <li>content 1</li>
 *      <li>content 2</li>
 *      <li>content 3</li>
 *  </ul>
 *  
 *  $('#news').innerfade({ 
 *	  animationtype: Type of animation 'fade' or 'slide' (Default: 'fade'), 
 *	  speed: Fading-/Sliding-Speed in milliseconds or keywords (slow, normal or fast) (Default: 'normal'), 
 *	  timeout: Time between the fades in milliseconds (Default: '2000'), 
 *	  type: Type of slideshow: 'sequence', 'random' or 'random_start' (Default: 'sequence'), 
 * 		containerheight: Height of the containing element in any css-height-value (Default: 'auto'),
 *	  runningclass: CSS-Class which the container getŐs applied (Default: 'innerfade'),
 *	  children: optional children selector (Default: null)
 *  }); 
 *

// ========================================================= */


(function($) {

    $.fn.innerfade = function(options) {
        return this.each(function() {   
            $.innerfade(this, options);
        });
    };

    $.innerfade = function(container, options) {
        var settings = {
        	'animationtype':    'fade',
            'speed':            'normal',
            'type':             'sequence',
            'timeout':          2000,
            'containerheight':  'auto',
            'runningclass':     'innerfade',
            'children':         null
        };
        if (options)
            $.extend(settings, options);
        if (settings.children === null)
            var elements = $(container).children();
        else
            var elements = $(container).children(settings.children);
        if (elements.length > 1) {
            $(container).css('position', 'relative').css('height', settings.containerheight).addClass(settings.runningclass);
            for (var i = 0; i < elements.length; i++) {
                $(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute').hide();
            };
            if (settings.type == "sequence") {
                setTimeout(function() {
                    $.innerfade.next(elements, settings, 1, 0);
                }, settings.timeout);
                $(elements[0]).show();
            } else if (settings.type == "random") {
            		var last = Math.floor ( Math.random () * ( elements.length ) );
                setTimeout(function() {
                    do { 
												current = Math.floor ( Math.random ( ) * ( elements.length ) );
										} while (last == current );             
										$.innerfade.next(elements, settings, current, last);
                }, settings.timeout);
                $(elements[last]).show();
						} else if ( settings.type == 'random_start' ) {
								settings.type = 'sequence';
								var current = Math.floor ( Math.random () * ( elements.length ) );
								setTimeout(function(){
									$.innerfade.next(elements, settings, (current + 1) %  elements.length, current);
								}, settings.timeout);
								$(elements[current]).show();
						}	else {
							alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
						}
				}
    };

    $.innerfade.next = function(elements, settings, current, last) {
        if (settings.animationtype == 'slide') {
            $(elements[last]).slideUp(settings.speed);
            $(elements[current]).slideDown(settings.speed);
        } else if (settings.animationtype == 'fade') {
            $(elements[last]).fadeOut(settings.speed);
            $(elements[current]).fadeIn(settings.speed, function() {
							removeFilter($(this)[0]);
						});
        } else
            alert('Innerfade-animationtype must either be \'slide\' or \'fade\'');
        if (settings.type == "sequence") {
            if ((current + 1) < elements.length) {
                current = current + 1;
                last = current - 1;
            } else {
                current = 0;
                last = elements.length - 1;
            }
        } else if (settings.type == "random") {
            last = current;
            while (current == last)
                current = Math.floor(Math.random() * elements.length);
        } else
            alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
        setTimeout((function() {
            $.innerfade.next(elements, settings, current, last);
        }), settings.timeout);
    };

})(jQuery);

// **** remove Opacity-Filter in ie ****
function removeFilter(element) {
	if(element.style.removeAttribute){
		element.style.removeAttribute('filter');
	}
}





/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright ĺ© 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeInOutSine',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	}
});






/// <reference path="../../../lib/jquery-1.2.6.js" />
/*
	Masked Input plugin for jQuery
	Copyright (c) 2007-2009 Josh Bush (digitalbush.com)
	Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) 
	Version: 1.2.2 (03/09/2009 22:39:06)
*/
(function($) {
	var pasteEventName = ($.browser.msie ? 'paste' : 'input') + ".mask";
	var iPhone = (window.orientation != undefined);

	$.mask = {
		//Predefined character definitions
		definitions: {
			'9': "[0-9]",
			'a': "[A-Za-z]",
			'*': "[A-Za-z0-9]"
		}
	};

	$.fn.extend({
		//Helper Function for Caret positioning
		caret: function(begin, end) {
			if (this.length == 0) return;
			if (typeof begin == 'number') {
				end = (typeof end == 'number') ? end : begin;
				return this.each(function() {
					if (this.setSelectionRange) {
						this.focus();
						this.setSelectionRange(begin, end);
					} else if (this.createTextRange) {
						var range = this.createTextRange();
						range.collapse(true);
						range.moveEnd('character', end);
						range.moveStart('character', begin);
						range.select();
					}
				});
			} else {
				if (this[0].setSelectionRange) {
					begin = this[0].selectionStart;
					end = this[0].selectionEnd;
				} else if (document.selection && document.selection.createRange) {
					var range = document.selection.createRange();
					begin = 0 - range.duplicate().moveStart('character', -100000);
					end = begin + range.text.length;
				}
				return { begin: begin, end: end };
			}
		},
		unmask: function() { return this.trigger("unmask"); },
		mask: function(mask, settings) {
			if (!mask && this.length > 0) {
				var input = $(this[0]);
				var tests = input.data("tests");
				return $.map(input.data("buffer"), function(c, i) {
					return tests[i] ? c : null;
				}).join('');
			}
			settings = $.extend({
				placeholder: " ",
				completed: null
			}, settings);

			var defs = $.mask.definitions;
			var tests = [];
			var partialPosition = mask.length;
			var firstNonMaskPos = null;
			var len = mask.length;

			$.each(mask.split(""), function(i, c) {
				if (c == '?') {
					len--;
					partialPosition = i;
				} else if (defs[c]) {
					tests.push(new RegExp(defs[c]));
					if(firstNonMaskPos==null)
						firstNonMaskPos =  tests.length - 1;
				} else {
					tests.push(null);
				}
			});

			return this.each(function() {
				var input = $(this);
				var buffer = $.map(mask.split(""), function(c, i) { if (c != '?') return defs[c] ? settings.placeholder : c });
				var ignore = false;  			//Variable for ignoring control keys
				var focusText = input.val();

				input.data("buffer", buffer).data("tests", tests);

				function seekNext(pos) {
					while (++pos <= len && !tests[pos]);
					return pos;
				};

				function shiftL(pos) {
					while (!tests[pos] && --pos >= 0);
					for (var i = pos; i < len; i++) {
						if (tests[i]) {
							buffer[i] = settings.placeholder;
							var j = seekNext(i);
							if (j < len && tests[i].test(buffer[j])) {
								buffer[i] = buffer[j];
							} else
								break;
						}
					}
					writeBuffer();
					input.caret(Math.max(firstNonMaskPos, pos));
				};

				function shiftR(pos) {
					for (var i = pos, c = settings.placeholder; i < len; i++) {
						if (tests[i]) {
							var j = seekNext(i);
							var t = buffer[i];
							buffer[i] = c;
							if (j < len && tests[j].test(t))
								c = t;
							else
								break;
						}
					}
				};

				function keydownEvent(e) {
					var pos = $(this).caret();
					var k = e.keyCode;
					ignore = (k < 16 || (k > 16 && k < 32) || (k > 32 && k < 41));

					//delete selection before proceeding
					if ((pos.begin - pos.end) != 0 && (!ignore || k == 8 || k == 46))
						clearBuffer(pos.begin, pos.end);

					//backspace, delete, and escape get special treatment
					if (k == 8 || k == 46 || (iPhone && k == 127)) {//backspace/delete
						shiftL(pos.begin + (k == 46 ? 0 : -1));
						return false;
					} else if (k == 27) {//escape
						input.val(focusText);
						input.caret(0, checkVal());
						return false;
					}
				};

				function keypressEvent(e) {
					if (ignore) {
						ignore = false;
						//Fixes Mac FF bug on backspace
						return (e.keyCode == 8) ? false : null;
					}
					e = e || window.event;
					var k = e.charCode || e.keyCode || e.which;
					var pos = $(this).caret();

					if (e.ctrlKey || e.altKey || e.metaKey) {//Ignore
						return true;
					} else if ((k >= 32 && k <= 125) || k > 186) {//typeable characters
						var p = seekNext(pos.begin - 1);
						if (p < len) {
							var c = String.fromCharCode(k);
							if (tests[p].test(c)) {
								shiftR(p);
								buffer[p] = c;
								writeBuffer();
								var next = seekNext(p);
								$(this).caret(next);
								if (settings.completed && next == len)
									settings.completed.call(input);
							}
						}
					}
					return false;
				};

				function clearBuffer(start, end) {
					for (var i = start; i < end && i < len; i++) {
						if (tests[i])
							buffer[i] = settings.placeholder;
					}
				};

				function writeBuffer() { return input.val(buffer.join('')).val(); };

				function checkVal(allow) {
					//try to place characters where they belong
					var test = input.val();
					var lastMatch = -1;
					for (var i = 0, pos = 0; i < len; i++) {
						if (tests[i]) {
							buffer[i] = settings.placeholder;
							while (pos++ < test.length) {
								var c = test.charAt(pos - 1);
								if (tests[i].test(c)) {
									buffer[i] = c;
									lastMatch = i;
									break;
								}
							}
							if (pos > test.length)
								break;
						} else if (buffer[i] == test[pos] && i!=partialPosition) {
							pos++;
							lastMatch = i;
						} 
					}
					if (!allow && lastMatch + 1 < partialPosition) {
						input.val("");
						clearBuffer(0, len);
					} else if (allow || lastMatch + 1 >= partialPosition) {
						writeBuffer();
						if (!allow) input.val(input.val().substring(0, lastMatch + 1));
					}
					return (partialPosition ? i : firstNonMaskPos);
				};

				if (!input.attr("readonly"))
					input
					.one("unmask", function() {
						input
							.unbind(".mask")
							.removeData("buffer")
							.removeData("tests");
					})
					.bind("focus.mask", function() {
						focusText = input.val();
						var pos = checkVal();
						writeBuffer();
						setTimeout(function() {
							if (pos == mask.length)
								input.caret(0, pos);
							else
								input.caret(pos);
						}, 0);
					})
					.bind("blur.mask", function() {
						checkVal();
						if (input.val() != focusText)
							input.change();
					})
					.bind("keydown.mask", keydownEvent)
					.bind("keypress.mask", keypressEvent)
					.bind(pasteEventName, function() {
						setTimeout(function() { input.caret(checkVal(true)); }, 0);
					});

				checkVal(); //Perform initial check for existing values
			});
		}
	});
})(jQuery);