var Penzu = function(){
    return {
        init : function(){
            if($('#frm_progift').length && $('#frm_progift input.datepkr:first').length){
                var $dp = $('#frm_progift input.datepkr:first'),
                    dpState = false;
                $.appendJS('/javascripts/datepicker-min.js');
                if(!$.browser.msie){ $.appendCSS('/stylesheets/datepicker-static.css'); }
                $dp.DatePicker({
                    event : 'click'
                    ,date : $dp.val()
                    ,current : $dp.val()
                    ,format : 'B d, Y'
                    ,calendars : 1
                    ,mode : 'single'
                    ,starts : 0
                    ,onBeforeShow : function(pkrElem){ 
                        $dp.DatePickerSetDate($dp.val(), true);
                    }
                    ,onChange : function(dateVal, dateObj, elem){ 
                		$dp.val(dateVal);
            			$dp.DatePickerHide();
                    }
                    ,onShow : function(dp){ }
                    ,onHide : function(dp){  }
                    ,onRender : function(date){
                        var now = new Date();
                        return {
                			disabled: (date.valueOf() <= now.valueOf())
                		}
                    }
                });
                $dp.siblings('a.datepkrbtn:first').bind('click', function(e){ e.preventDefault(); dpState ? $dp.DatePickerHide() : $dp.DatePickerShow(); dpState = !dpState; });
				$('body').append('<div id="imgmodal" class="jqmWindow image"></div>');
                $('#imgmodal').jqm({trigger: 'a.imgmodal',
                        onShow: function(hash){ 
                            var t = $(hash.t), 
                                w = $(hash.w);
                            w.load($(hash.t).attr('href'), function(){
                                w.jqmAddClose($('a.jqmClose', w));
                                w.fadeIn('normal');
                            });
                        },
                        onHide: function(hash){ 
                            hash.w.fadeOut('fast', function(){ hash.o.remove(); $(hash.w).html(''); });
                        }
                });
            };
			if($('#user_tz_offset').length) {
				function FindGmtOffset() {
			        var year = new Date().getYear();
			        if (year < 1000)
			            year += 1900;			
			       	var currentDate = new Date();			
			        var firstSwitch = 0;
			        var secondSwitch = 0;
			        var lastOffset = 99;
			        var firstDifference = 0;
			        var secondDifference = 0;			
			        // Loop through every month of the current year
			        for (i = 0; i < 12; i++) {
			            // Fetch the timezone value for the month
			            var newDate = new Date(Date.UTC(year, i, 0, 0, 0, 0, 0));
			            var tz = -1 * newDate.getTimezoneOffset() / 60;			
			            // Capture when a timzezone change occurs
			            if (tz > lastOffset) {
			                firstSwitch = i-1;
			                firstDifference = (tz - lastOffset)*60*60;
			            } else if (tz < lastOffset) {
			                secondSwitch = i-1;
			                secondDifference = (lastOffset - tz)*60*60;
			            }			
			            lastOffset = tz;
			        }			
			        // Go figure out date/time occurences a minute before
			        // a DST adjustment occurs
			        var secondDstDate = FindDstSwitchDate(year, secondSwitch);
			        var firstDstDate = FindDstSwitchDate(year, firstSwitch);			
					// Add the DST adjustment if necessary
					if(currentDate >= firstDstDate && currentDate <= secondDstDate)
						return -1*((new Date).getTimezoneOffset()*60+firstDifference);
					else
						return -1*((new Date).getTimezoneOffset()*60);			
			    }			
			    function FindDstSwitchDate(year, month) {
			        // Set the starting date
			        var baseDate = new Date(Date.UTC(year, month, 0, 0, 0, 0, 0));
			        var changeDay = 0;
			        var changeMinute = -1;
			        var baseOffset = -1 * baseDate.getTimezoneOffset() / 60;
			        var dstDate;			
			        // Loop to find the exact day a timezone adjust occurs
			        for (day = 0; day < 50; day++) {
			            var tmpDate = new Date(Date.UTC(year, month, day, 0, 0, 0, 0));
			            var tmpOffset = -1 * tmpDate.getTimezoneOffset() / 60;			
			            // Check if the timezone changed from one day to the next
			            if (tmpOffset != baseOffset) {
			                var minutes = 0;
			                changeDay = day;			
			                // Back-up one day and grap the offset
			                tmpDate = new Date(Date.UTC(year, month, day-1, 0, 0, 0, 0));
			                tmpOffset = -1 * tmpDate.getTimezoneOffset() / 60;			
			                // Count the minutes until a timezone chnage occurs
			                while (changeMinute == -1) {
			                    tmpDate = new Date(Date.UTC(year, month, day-1, 0, minutes, 0, 0));
			                    tmpOffset = -1 * tmpDate.getTimezoneOffset() / 60;			
			                    // Determine the exact minute a timezone change occurs
			                    if (tmpOffset != baseOffset) {
									// Back-up a minute to get the date/time just
									// before a timezone change occurs
									tmpOffset = new Date(Date.UTC(year, month, day - 1, 0, minutes - 1, 0, 0));
									changeMinute = minutes;
									break;
								}
								else {
									minutes++;
								}
			                }			
			                tmpDate = new Date(Date.UTC(year, month,
			                                   day-1, 0, minutes-1, 0, 0));
			                return tmpDate;
			            }
			        }
			    }
				$('#user_tz_offset').val(FindGmtOffset());
			}
        },
        Header : { notice : function(){ return; }},
        nifty_options : 'small transparent',
        nifty_bot_options : 'small transparent bl br',
        aj : function(e){
            e.preventDefault();
            var a = $(e.target), data = '', u;
            if(!a.is('a')){
                if($(e.target).parent().is('a')){ a = $(e.target).parent(); }
            }
            if(null == a || !a.length || a.hasClass('disabled')){ return false; }
            u = a.attr('href');
            if($.string(a.attr('href')).include('?')){
                if(!$.string(data).blank() && !$.string(data).startsWith('&')){ data += '&'; }
                data += a.attr('href').substr(a.attr('href').indexOf('?') + 1);
            }
            if(a.hasClass('form')) {
                // add form contents to request
                if(!$.string(data).blank() && !$.string(data).startsWith('&')){ data += '&'; }
                data += a.parents('form:first').serialize();
                u = a.parents('form:first').attr('action');
            }
            if(a.hasClass('jqm') || a.hasClass('jqmi')){
               a.hasClass('jqm') ? $('#modal').jqmShow(a) : $('#imodal').jqmShow(a);
            }
            else if(a.hasClass('post')) {
                $.post(u, data);
            } else if(a.hasClass('json')) {
                $.getJSON(u, data);
            } else if(a.hasClass('script')) {
                $.getScript(u);
            } else if(a.hasClass('pscript')) {
                $.ajax({
                    type: "POST",
                    url: u,
                    dataType: "script",
                    data: data,
                    complete: function(req, stat){ if(a.hasClass('form')) { restart_form(a); }}
                });
            } else {
                $.get(u, data, function (data, textStatus){
                    
                });
            }
            function restart_form(elem){
                if(!elem.is('form')){
                    elem = elem.parents('form:first');
                }
                $('a.submit', elem).show(); $('img.throb', elem).hide();
            }
        },
        handle_click : function(e){
            if($.isRightClick(e)) return;
            var clicked = $(e.target),
                self = this;
            if(!clicked.is('a')){
                if($(e.target).parent().is('a')){ clicked = $(e.target).parent(); }
            }
            if(clicked.is('a') || clicked.is('input') || clicked.is('select')){
                var self = this;
                var cnames = clicked.classNames();
                if(!cnames.length) return;
                $.each(cnames, function(i,c) {
                    try {
                        if($.isFunction(eval("self." + c))){
                            eval("self." + c + "(e);")
                            e.preventDefault();
                        }
                    } catch(er){};
                });
            }
        },
        do_paypal : function(elem){
            elem = $(elem);
            if(elem.is('select')){
                if(elem.val() === 'paypal'){
                    $('#midfs').hide();
                    $('#gp_promo_code').show();
                    $('#botfs').show();
                    if($.browser.msie && $.browser.version.indexOf('7') == 0){ $('#pagesh_bot').css('top', 10); }
                } else if (elem.val() !== '') {
                    $('#midfs').show();
                    $('#gp_promo_code').show();
                    $('#botfs').show();
                    if($.browser.msie && $.browser.version.indexOf('7') == 0){ $('#pagesh_bot').css('top', 10); }
                } else {
                    $('#midfs').hide();
                    $('#gp_promo_code').hide();
                    $('#botfs').hide();
                }
            }
        },
        handle_key : function(e){
            var code;
            if(e.keyCode){ code = e.keyCode; }
            else{ code = e.which; }
            if(code == 13){
                if($(e.target).is('textarea')){ return; }
                if($(e.target).is('input')){
                    var form = $(e.target).parents('form.return:first');
                    if(form.length > 0){
                        if(form.hasClass('bhide')){
                            $('a.submit', form).hide();
                        }
                        if(form.hasClass('nthrob')) {
                            $('img.throb', form).show();
                        }
                        if(form.hasClass('aj')) {
                            $.post(form.attr('action'), form.serialize(), function(data, textStatus){ $('a.submit', form).show(); $('img.throb', form).hide(); }, 'script');
                        } else {
                            form.submit();
                        }
                    }
                }
            }
        },

        submit : function(e){
            var a = this.get_link(e);
            if(a.length&&!a.hasClass('disabled')){
                var f = a.parents('form:first');
                if(f.length) f.submit();
            }
        },
        get_link : function(e){
            if(typeof(e.target) != 'undefined' && !$(e.target).is('a')){
                return $(e.target).parents('a:first');
            } else {
                return $(e.target);
            }
        }
        ,hashToggle : function(e){
            var c = $(e.target), h, t;
            if(!c.is('a')) c = c.parents('a:first');
            if(!c.is('a')) return;
            var h = c.attr('href');
            t = $(h.slice(c.attr('href').indexOf('#')));
            if(t.length){
                e.preventDefault();
                t.toggle();
                if(c.hasClass('stoggle'))
                    $.each($("a.hashToggle[href*='" + h + "']"), function(i, a){c.is(':visible') ? $(a).hide() : $(a).show();});
                if(c.hasClass('sopen'))
                    c.toggleClass('open');
                if(c.hasClass('otoggle')){
                    t.is(':visible') ?
                        $("a.hashToggle[href*='" + h + "']").addClass('open') :
                        $("a.hashToggle[href*='" + h + "']").removeClass('open');
                }
            }
            return false;
        }
    };
}();

$(document).ready(function(){

    Penzu.init();
    $('.nifty').nifty(Penzu.nifty_options);
    $(document).bind('click', function(e){ Penzu.handle_click(e); });
    $(document).bind('keyup', function(e){ Penzu.handle_key(e); });
    $('form').gvform();
   
   function load_nested(w){
       $('a.jmodal', w).bind('click', function(e){
           e.preventDefault();
           w.load($(e.target).attr('href'), function(e){
               $('form', w).gvform();
               $('.nifty', w).nifty(Penzu.nifty_options);
               w.jqmAddClose($('a.jqmClose', w));
               load_nested(w);
           });
       });
   }
   $('#modal').jqm({trigger: 'a.jmodal', 
           onShow: function(hash){ 
               var t = $(hash.t), 
                   w = $(hash.w),
                   d = '';
               if(t.hasClass('form')){
                   if(t.parents('form:first').length > 0){
                       d += t.parents('form:first').serialize();
                   }
               }
               if(t.hasClass('pad')){
                   if($('form.main').length > 0){
                       d += $('form.main').serialize();
                   }
               }
               if(t.hasClass('video')) w.addClass('wide');
               else w.removeClass('wide');
               w.load($(hash.t).attr('href'), d, function(){
                   load_nested(w);
                   w.jqmAddClose($('a.jqmClose', w));
                   $('.nifty', w).nifty(Penzu.nifty_options);
                   if(t.hasClass('buttons')){
                   	$("a.tryBtn", w).hover(function() {
                   		$("span.noSignUpReq", w).css({'background-position' : '-106px 0'});
                   	});
                   	$("a.tryBtn", w).mousedown(function() {
                   		$("span.noSignUpReq", w).css({'background-position' : '-212px 0'});
                   	});
                   	$("a.tryBtn", w).mouseout(function() {
                   		$("span.noSignUpReq", w).css({'background-position' : '0 0'});
                   	});
                   }
                   w.fadeIn('normal', function(){ $('form', w).gvform(); });
               });
           },
           onHide: function(hash){ 
               hash.w.fadeOut('fast', function(){ hash.o.remove(); $(hash.w).html(''); });
           }
   });
});
