AJAX = {
		frame : function(c) {
		    var n = 'f' + Math.floor(Math.random() * 99999);
		    var d = document.createElement('DIV');
		    d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AJAX.loaded(\''+n+'\')"></iframe>';
		    document.body.appendChild(d);
		    var i = document.getElementById(n);
		    if (c && typeof(c.onComplete) == 'function') {
			i.onComplete = c.onComplete;
		    }
		    return n;
		},
	    
		form : function(f, name) {
		    f.setAttribute('target', name);
		},
	    
		submit : function(f, c) {
		    AJAX.form(f, AJAX.frame(c));if (c && typeof(c.onStart) == 'function') {return c.onStart();} else {return true;}
		},
	    
		loaded : function(id) {
		    var i = document.getElementById(id);
		    if (i.contentDocument) {
			var d = i.contentDocument;
		    } else if (i.contentWindow) {
			var d = i.contentWindow.document;
		    } else {
			var d = window.frames[id].document;
		    }
		    if (d.location.href == "about:blank") {
			return;
		    }
		    if (typeof(i.onComplete) == 'function') {
			i.onComplete(d.body.innerHTML);
		    }
		}
	}

var ima = 0;
var tday = '';
var tdayc = '';
if(typeof this.PINT=="undefined"){var PINT={}; }

PINT.modalOverlay = false;
PINT.calendarInfo = [];

/*
if (!$.cookie('ZINGcalendar')) {
	$.cookie('ZINGcalendar', '', { path : '/', expires : 60 });
} else {
	PINT.calendarInfo = $.cookie('ZINGcalendar').split(',');
}
*/

/* FUNCTIONS *******************/

/* GET LOCATION ON CLICK **********/
// Format: $('.something').PINT_getLocationOnClick('http://www.zingchart.com/');
$.fn.PINT_getLocationOnClick = function(url) {
    if ( $(this).length ) {
        $(this).bind('click',function() {
            window.location = url;
        });
    }
}

/* CALENDAR ACTION **********/
// Sets Action on calendar click
// Format: $('.list-calendar').PINT_calendar();
$.fn.PINT_calendar = function(startOffset) {
    if ( $(this).length ) {

        // Set negative offset value
        var negOffset = '-'+startOffset;
        // Set timing constant so animations run at same intervals
        var fadeTiming = 300;
        var timing = 500;
        var fade = .3;

        // FIND EACH 'NON-ACTIVE' A
        // Find each A tag inside our calendar list
        $(this).find('a').each(function() {

            // Remove non-JS CSS
            $(this).css({ 'opacity':'1','background':'none' });

            // HOVER: **********/
            // When you HOVER on an 'non-active' A tag

            // Mouse Enter
            $(this).mouseenter(function() {

                // If 'Active' state link
                if ( $(this).parent().hasClass('active') ) {

                    $(this)
                    // Fade in hover
                    .children('.day').addClass('hover')
                        .children('span')
                            .stop()
                            .css('opacity','.3')
                            .animate({ opacity:'1' }, fadeTiming, function() {})

                }
                // Non-active day links
                else {

                    $(this)
                        // Fade in hover
                        .children('.day').addClass('hover')
                            .children('span')
                                .stop()
                                .css('opacity','0')
                                .animate({ opacity:'.14' }, fadeTiming, function() {})
                                .end()
                            .children('strong')
                                .stop()
                                .css('opacity','1')
                                .animate({ opacity:'.5' }, fadeTiming, function() {})
                    ;

                }

            });

            // Mouse Leave
            $(this).mouseleave(function() {
                $(this)
                    .children('.day')
                        .children('span')
                            .stop()
                            .animate({ opacity:'0' }, fadeTiming, function() {})
                            .end()
                        .children('strong')
                            .stop()
                            .animate({ opacity:'1' }, fadeTiming, function() {})
                ;
            });

        });

		function PINT_calendarActivateDay(aObj, bRaiseOverlay) {
        	if ($(aObj).length == 0) {
        		return;
        	}
			var sDay = $(aObj).attr('href').replace('#day', '');
        	if ($.inArray(sDay, PINT.calendarInfo) == -1) {
        		PINT.calendarInfo.push(sDay);
        		$.cookie('ZINGcalendar', PINT.calendarInfo.join(','), { path : '/', expires : 60 });
        	}
        	$(aObj)
                .stop()
                .animate({ opacity:'1' }, 800, function() {})
                // Add class to remove CSS shadow once active A clicked
                .parent()
                .addClass('remove-css')
                .end()

                // Find '.day' element to slide 'out'
                .children('.day')
                    // Add '.day-active' so background gradient stays if you hover off
                    .addClass('day-active')
                    .animate({ left:negOffset }, timing, function() {

                        // Remove class when anim finishes to remove solid-state class for normal hover functionality
                        $(this).removeClass('day-active');
			if(ima == 1){
				if (bRaiseOverlay) {
				    // Run OVERLAY MAIN code
				    $(this).PINT_overlayMain();
				}
			}
                    })

                // Return focus back to 'this' (.active a)
                .end()

                // Then find the 'current' .content box
                .children('.content')
                // slide 'in' .content while .day slides 'out'
                    .animate({ marginLeft:'0' }, timing, function() {})
            ;
        }

		$.each(PINT.calendarInfo, function() {
			PINT_calendarActivateDay($('a[href=#day' + this.toString() + ']'), false);
		});

        // FIND EACH 'ACTIVE' A
        // Find each A tag inside our calendar list
        $(this).find('.active a').each(function() {

            /* MOUSE DOWN: **********/
            // When you MOUSE DOWN/UP on an 'active' A tag
            $(this)
                // Mousedown
                .bind('mousedown', function() {
                    $(this)
                        .animate({ opacity:'.7' }, 600, function() {})
                        .parent().addClass('remove-css');
                })
            ;

            /* CLICK: **********/
            // When you CLICK on an 'active' A tag
            $(this).bind('click', function() {
		if($(this).hasClass('ima')){
			ima = 1;
		}
		else {
			ima = 0;
		}
                // Actions
		PINT_calendarActivateDay(this, true);
		// Return false on the first click since we don't want to run the A tag HREF yet
		return false;
		
            });

        });

    }
};

/* HEADLINE FADE **********/
// Fades in Headlines (H1,H2)
// Format: $('h1.headline').PINT_headlineFade();
$.fn.PINT_headlineFade = function() {
    if ( $(this).length ) {
		var self = this;
		$(this)
        	.next()
        		.css({ 'opacity':'0' })
		$(this)
        	.next().next()
        		.css({ 'opacity':'0', 'margin-left':'100px' })

		$(this)
        	.next().next().next()
        		.css({ 'opacity':'0' })

        $(this)
        	.css({ 'opacity':'0', 'margin-left':'-200px' })
        	.animate({ opacity:'1', marginLeft:'0' }, 450, function() {

		        $(self)
		        	.next().next()
			        	.animate({ opacity:'1', marginLeft:'-60px' }, 450, function() {
			        		window.setTimeout(function() {
						        $(self)
						        	.next().next()
				        				.animate({ opacity:'1', marginLeft:'0' }, 450, function() {
											$(self)
									        	.next()
									        		.animate({ opacity:'1' }, 450, function() {
									        			$(self)
									        				.next().next().next()
									        					.animate({ opacity:'1' }, 450, function() {});
									        		});
				        				});
			        		}, 250);
			        	});

        	})
    }
};

window.onresize = function() {
    $('body').PINT_setOverlayPosition(false);
}
window.onscroll = function() {
	$('body').PINT_setOverlayPosition(false);
}

/* OVERLAY MAIN **********/
// Creates MAIN OVERLAY Box
$.fn.PINT_overlayMain = function(empty) {

	if (typeof(empty) == 'undefined') {
		empty = false;
	}

	if (empty) {

		$('#overlay-main').remove();
		$('#overlay-mask').remove();

	    var overlayCode = '<div id="overlay-main"><div id="overlay-body"><div id="overlay-close">Close<span>&nbsp;</span></div></div></div>';

	    $('body').prepend('<div id="overlay-mask"></div>');
		$('#overlay-mask').css({'opacity':0.65,'width':$(window).width(),'height':$(document).height()}).show();

        $('body').prepend( $(overlayCode).css('opacity','0') );

	    if ($('#overlay-close').length) {
	    	$('#overlay-close').bind('click', function () {
    			$('#overlay-mask').animate({ opacity:'0' }, 350, function() {
	    			$(this).remove();
	    		});
	    		$(this).parent().parent().animate({ opacity:'0' }, 350, function() {
	    			$(this).remove();
	    		});
	    	});
	    }

	} else {

	    var ordinal = $(this).find('strong').text();
	    var selectedDay = '#day'+ordinal;
	    var selectedDayCode = $(selectedDay).html();
	    tday = selectedDay;
	    tdayc = selectedDayCode;
	    $(selectedDay).html(' ');
	    var closeCode = '<div id="overlay-close"><img src="../../../swcms4/slices/icons/delete.png" /><span>&nbsp;</span></div>';
	    var overlayCode = '<div id="overlay-main"><div id="overlay-body">'+selectedDayCode+closeCode+'</div></div>';

	    // MAIN OVERLAY CODE
	    if (PINT.modalOverlay) {
			if (!$('#overlay-mask').length) {
				$('body').prepend('<div id="overlay-mask"></div>');
			}
			$('#overlay-mask').css({'opacity':0.65,'width':$(window).width(),'height':$(document).height()}).show();
	    }

	    var init = true;
	    if (!$('#overlay-main').length) {
	        $('body').prepend( $(overlayCode).css('opacity','0') );
	    } else {
	    	init = false;
	    	$('#overlay-body').html(selectedDayCode+closeCode);
	    }

		$('body').PINT_setOverlayPosition(init);
	    if ($('#overlay-close').length) {
	    	$('#overlay-close').bind('click', function () {
	    		if (PINT.modalOverlay) {
	    			$('#overlay-mask').animate({ opacity:'0' }, 350, function() {
		    			$(this).remove();
		    		});
	    		}
	    		$(this).parent().parent().animate({ opacity:'0' }, 350, function() {
	    			$(this).remove();
	    		});
			$(tday).html(tdayc);
			$('#s'+ordinal).fadeOut('fast');
	    	});
	    }
	}
	$('.tip').tipsy({fade: true});
	$('.edible').aloha();
	
	$('#s'+ordinal).fadeIn('slow');
	
	$.post('../../../ajax.php', {ordinal: ordinal, aji: 44});
}

/* OVERLAY POSITIONING **********/
// Position OVERLAY Box
$.fn.PINT_setOverlayPosition = function(init) {
	if ($('#overlay-main').length) {
 		overlayTop = $(window).scrollTop() + parseInt(($(window).height() - $('#overlay-body').height())/2);
		overlayLeft = parseInt(($(window).width() - $('#overlay-body').width())/2);
		if (init) {
	        $('#overlay-main')
	        	.css('left', overlayLeft + 'px')
	        	.css('top', overlayTop + 'px')
				.css('width', $('#overlay-body').width() + 'px')
				.css('height', $('#overlay-body').height() + 'px')
	        	.animate({ opacity:'1' }, 350, function() {});
		} else {
			$('#overlay-main')
				.animate({
					top : overlayTop + 'px',
					left : overlayLeft + 'px',
					width : $('#overlay-body').width() + 'px',
					height : $('#overlay-body').height() + 'px'
				}, 350, function() {});
		}
	}
}

/* OVERLAY BOX **********/
// Format: $('#trigger').PINT_overlayBox('#target');
$.fn.PINT_overlayBox = function(tgt,timing,type) {
    if ( $(this).length ) {

        var triggerXpos = $(this).position().left; // Starting X position of trigger
        var triggerYpos = $(this).position().top; // Starting Y position of trigger

        var triggerWidth = $(this).width(); // Starting WIDTH of trigger
        var tgtWidth = $(tgt).width(); // Starting WIDTH of target
        var tgtHeight = $(tgt).height(); // Starting HEIGHT of target
        var closeCode = '<span class="close"><img src="../../../swcms4/slices/icons/delete.png" /><span>&nbsp;</span></span>'; // Close button markup
        var setType = type || false;
        // Height/Ypos Calcs

        var tgtYPOSCalc = ((triggerYpos-tgtHeight)-16); // Find difference between Trigger Y and the HEIGHT of Target (then subtract the height of the 'arrow' graphic
        var tgtYPOSOffset = tgtYPOSCalc+20; // Calculate the new value if we add an offset amount (will determine starting position so we can 'slide' to correct spot
        var tgtYPOSend = tgtYPOSCalc+'px'; // Convert to pixels
        var tgtYPOSstart = tgtYPOSOffset+'px'; // Convert to pixels

        if (setType == 'right') {

            // Width/Xpos Calcs
            var containingBoxWidth = $('#container').width(); // Find the width of the containing column
            var triggerRightEdge = triggerXpos+triggerWidth; // Find the right edge of Trigger
            var rightEdgeDiff = (containingBoxWidth-triggerRightEdge)+'px'; // Find the difference in pixels

            // Set Starting CSS Paramaters
            $(tgt)
                .hide()
                .css({ 'visibility':'visible', 'opacity':'0', 'position':'absolute', 'top':tgtYPOSstart, 'right':rightEdgeDiff })
                .append(closeCode)
            ;

        } else {

            // Width/Xpos Calcs
            var widthDiff = (triggerWidth-tgtWidth); // Find difference between Trigger WIDTH and Target WIDTH
            var widthDiffHalf = Math.ceil(widthDiff/2); // Divide by 2 then round up to nearest integer
            var tgtXPOSstart = (widthDiffHalf)+'px'; // Convert to pixels

            // Set Starting CSS Paramaters
            $(tgt)
                .hide()
                .css({ 'visibility':'visible', 'opacity':'0', 'position':'absolute', 'top':tgtYPOSstart, 'left':tgtXPOSstart })
                .append(closeCode)
            ;
        }

        var semaphore = { allowMouseEnter : false, mouseEnter : false };

        // Trigger Actions
        $(this).hover(function() {
            $(tgt).show().animate({ opacity:'1', top:tgtYPOSend }, timing, function() { semaphore.allowMouseEnter = true; });
            return false;
        });

        // Target Actions
        $(tgt)
            // Add Class to last P
            .children()
                .find('p:last-child').addClass('last')
            .end().end()
            // Action for 'Close Button'
            .find('.close')
                .click(function() {
                    $(tgt).stop().animate({ opacity:'0', top:tgtYPOSstart }, timing, function() { $(this).hide();semaphore.allowMouseEnter = semaphore.mouseEnter = false; })
        });

        $(tgt)
    		.mouseenter(function() {
    			if (semaphore.allowMouseEnter) {
    				semaphore.mouseEnter = true;
    			}
	        })
	        .mouseleave(function() {
	        	if (semaphore.mouseEnter) {
	        		$(this).stop().animate({ opacity:'0', top:tgtYPOSstart }, timing, function() { $(this).hide();semaphore.allowMouseEnter = semaphore.mouseEnter = false; })
	        	}
	        });
	}
    
	
};

/* SHARE MENU *********
// Creates Share Menu on load
// Format: $('#header').PINT_share();
$.fn.PINT_share = function(timing) {
    if ( $(this).length ) {

        var shareCode = [
                '<div id="share">',
                '    <ul>',
                '        <li><a id="share-facebook" href="javascript:;" class="icon-facebook">Facebook<span>&nbsp;</span></a></li>',
                '        <li><a id="share-twitter" href="javascript:;" class="icon-twitter">Twitter<span>&nbsp;</span></a></li>',
                '        <li><a id="share-bookmark" href="javascript:;" class="icon-bookmark">Bookmark This Page<span>&nbsp;</span></a></li>',
                '        <li><a id="share-email" href="javascript:;" class="icon-share">Share Page With a Friend<span>&nbsp;</span></a></li>',
                '    </ul>',
                '    <p>Share</p>',
                '</div>'
            ].join('');

        $(this).append(

            $(shareCode)
                .mouseenter(function() {
                    $(this)
                        .stop()
                    	.animate({ top:'0' }, timing, function() {})
                        .children('p').text('Close');
                })
                .mouseleave(function() {
                    $(this)
                        .stop()
                        .animate({ top:'-146px' }, timing, function() {})
                        .children('p').text('Share');
                })
                .click(function() {
                	if (parseInt($(this).css('top'), 10) == 0) {
	                    $(this)
	                        .stop()
	                        .animate({ top:'-146px' }, timing, function() {})
	                        .children('p').text('Share');
                	} else {
	                	$(this)
	                        .stop()
	                    	.animate({ top:'0' }, timing, function() {})
	                        .children('p').text('Close');
                	}
                })
        );

        $('#share-facebook').click(function() {
        	window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(window.location.href), 'fbwin', 'height=440,width=620');
        });
        $('#share-twitter').click(function() {
	        window.open('http://twitter.com/home?status=' + encodeURIComponent("I unlocked the final HTML5 Advent(ure)! Snow Globe Five-Oh: Create and send custom HTML5 snow globes.") + '+-+' + encodeURIComponent(window.location.href), 'twitterwin', 'height=650,width=1024,scrollbars=yes');
        });
        $('#share-bookmark').click(function() {
        	PINT.bookmarkPage(encodeURIComponent(document.title), encodeURIComponent(window.location.href));
		});
	    $('#share-email').click(function() {
			$(this).PINT_overlayMain(true);
			$('#overlay-body').prepend([
				'<div id="share-form">',
					'<h1>Share This Item With A Friend</h1>',
					'<div><label for="share-your-name">Enter your name:</label></div>',
					'<div><input type="text" id="share-your-name" /><br />&nbsp;<span class="share-error" id="share-your-name-error">Please enter your name...</span></div>',
					'<div><label for="share-friends-emails">Add friends email addresses below separated by a comma:</label></div>',
					'<div><input type="text" id="share-friends-emails" /><br />&nbsp;<span class="share-error" id="share-friends-emails-error">Please enter the email addresses...</span></div>',
					'<div><label for="share-message">Type in your message to your friends in the space below:</label></div>',
					'<div><textarea id="share-message"></textarea><br />&nbsp;<span class="share-error" id="share-message-error">Please enter your message...</span></div>',
					'<div><button id="share-submit">Send Email</button><span id="share-status"></span></div>'
			].join(''));
			$('body').PINT_setOverlayPosition(true);
			$('#share-submit').click(function() {
				$('.share-error').hide();
				error = false;
				$.each(['share-your-name', 'share-friends-emails', 'share-message'], function() {
					if ($.trim($('#'+this).val()) == '') {
						$('#'+this+'-error').show();
						error = true;
					}
				});
				if (error) {
					return;
				}
				var postdata = [
					'your_name=' + encodeURIComponent($('#share-your-name').val()),
					'friends_emails=' + encodeURIComponent($('#share-friends-emails').val()),
					'message=' + encodeURIComponent($('#share-message').val()),
					'url=' + encodeURIComponent(window.location.href)
				].join('&');
				$('#share-submit').attr('disabled', 'disabled');
				$('#share-status').html('<span class="share-notice">Wait...</span>');
				jQuery.ajax({
					type : 'POST',
					url : 'share.php',
					dataType : 'text',
					data : postdata,
					error : function(oXHR, sStatus, oError) {
						$('#share-status').html('<span class="share-error">An error has occured while sending the emails!</span>');
						$('#share-submit').attr('disabled', '');
					},
					success : function(sResponse, sStatus, oXHR) {
						var oResponse = eval('('+sResponse+')');
						if (typeof(oResponse['result']) != 'undefined' && oResponse['result'] == 1) {
							$('#share-status').html('<span class="share-notice">Your message has been sent!</span>');
						} else {
							$('#share-status').html('<span class="share-error">An error has occured while sending the emails!</span>').find('span').show();
						}
						$('#share-submit').attr('disabled', '');
					}
				});
			});
		});
    }
};

PINT.bookmarkPage = function(title, url) {
	if (window.sidebar) {
		window.sidebar.addPanel(title, window.location, '');
	} else {
		if (window.opera && window.print) {
			var elem = document.createElement('a');
			elem.setAttribute('href', url);
			elem.setAttribute('title', title);
			elem.setAttribute('rel', 'sidebar');
			elem.click();
		} else {
			if (document.all) {
				window.external.AddFavorite(window.location, title);
			}
		}
	}
};

*/
PINT.init = function(){

    // Set JS class
    $('body').addClass('js-enabled');
    $('#header p').hide();

    // Initialize Calendar
    $('.component-calendar').PINT_calendar('126px');

    $('#zingchart-box .text').PINT_getLocationOnClick('http://www.zingchart.com/html5_rocks/');
    
    // Add 'Share' Menu
    //$('#header').PINT_share(450);

    // Headline Anims
    $('.headline-first').PINT_headlineFade();

    // Add 'Box' Overlays
    $('#contact').PINT_overlayBox('#contact-box',250);
    $('#zingchart').PINT_overlayBox('#zingchart-box',250,'right');

};

$(document).ready(function(){
  PINT.init();
});
