if( typeof window.zoom == 'undefined' ) {
    window.zoom = {};
    var zoom = window.zoom;
}

(function($) {
    
    $(document).ready(function() {
        zoom.testimonials();
        zoom.theFinalCountdown();
        zoom.inputDefaults();
        zoom.registrationForm();
        zoom.truncateSections();
        $('.social-networks a').qtip({
            'style': {
                'background': '#d2edf7',
                'border': {
                    'width': 5,
                    'radius': 5,
                    'color': '#1da5d9'
                },
                'color': '#1da5d9',
                'fontWeight': 'bold',
                'textAlign': 'center',
                'tip': 'bottomMiddle',
                'width': 200
            },
            'position': {
                'corner': {
                    'target': 'topMiddle',
                    'tooltip': 'bottomMiddle'
                }
            }
        });
        $('a[rel=external]').attr({'target':'_blank'});
    });
    
    $(window).load(function() {
        zoom.slideshow();
    });
    
    zoom.testimonials = function() {
        var section = $('.section-workamajig');
        
        var protos = {
            'link': $('<a href="#show-testimonials" title="View testimonials">Testimonials</a>')
        }
        
        if( section.size() ) {
            var origHeight = section.height();
            
            var quotes = section.find('blockquote');
            
            quotes.hide();

            var closedHeight = section.height();

            section.css({
                'overflow': 'hidden',
                'height': closedHeight
            });
            
            quotes.show();
            
            var para = section.children('p');

            var diff = section.height() - para.height();
            
            origHeight += diff;
            
            var link = protos.link.clone();
            var secondLink = protos.link.clone();
            var links = link.add(secondLink);

            links.click(function(c) {
                c.preventDefault();

                if( section.is(':animated') ) { return; } // let's not go crazy here
                
                section.animate({
                    'height': link.is('.on') ? closedHeight : origHeight + 'px'
                }, 1000, 'easeOutSine');
                
                if( link.is('.on') ) {
                    links.text('Testimonials').attr({'title': 'View testimonials'});
                } else {
                    links.text('Hide Testimonials').attr({'title': 'Hide testimonials'});
                }
                
                links.toggleClass('on');
            });

            para.html( para.html() + ' ' ).append( link );
            
            section.children(':last-child').append( secondLink );
            
            para.css({
                'margin-bottom': ( diff ) + 'px'
            });
        }
    };
    
    zoom.theFinalCountdown = function() {
        var earlyPara = $('div.register p.earlybird[title]');
        var para = $('div.register p.deadline[title]');
        
        if( ! para.size() || ! earlyPara.size() ) { return; }
        
        var deadline = new Date( para.attr('title') );
        var earlybird = new Date( earlyPara.attr('title') );
        if ( deadline == "Invalid Date" && earlybird == "Invalid Date" ) {
            return;
        }
        
        var now = new Date();
        if( now >= earlybird ) {
            earlyPara.remove();
            var isEarly = false;
        } else {
            deadline = earlybird;
            para.remove();
            para = earlyPara;
            var isEarly = true;
        }

        var paraPassed = $('<p class="deadline">The ' + ( isEarly ? 'early-bird' : 'registration' ) + ' deadline has passed.</p>');
		

        if( now >= deadline ) {
            para.replaceWith( paraPassed );
            return;
        }
        
        var padTime = function( value ) {
            if ( value < 10 ) {
                value = '0' + String( value );
            }
            return value;
        };
        
        var table = $('<table class="the-final-countdown"><tr><th>days</th><th>hours</th><th>minutes</th><th>seconds</th></tr><tr><td rel="days"></td><td rel="hours"></td><td rel="minutes"></td><td rel="seconds"></td></tr></table>');
        
        var cells = { 'days': table.find('td[rel=days]'), 'hours': table.find('td[rel=hours]'), 'minutes': table.find('td[rel=minutes]'), 'seconds': table.find('td[rel=seconds]') };
        
        var diff = ( ( ( now - deadline ) * ( 0 - 1 ) / 1000) ); // get the time difference in milliseconds, convert it to a positive number, the convert it to seconds
        
        var values = {};
        values.days = Math.floor( diff / 86400 );
        diff -= ( values.days * 86400 );
        values.hours = Math.floor( diff / 3600 );
        diff -= ( values.hours * 3600 );
        values.minutes = Math.floor( diff / 60 );
        diff -= ( values.minutes * 60 );
        values.seconds = Math.floor( diff );
        
        var insertTime = function() {
            cells.days.text( values.days );
            cells.hours.text( values.hours );
            cells.minutes.text( padTime( values.minutes ) );
            cells.seconds.text( padTime( values.seconds ) );
        };

        var updateTime = function() {
            values.seconds -= 1;
            if( values.seconds < 0 ) {
                values.seconds = 59;
                values.minutes -= 1;
            }
            if( values.minutes < 0 ) {
                values.minutes = 59;
                values.hours -= 1;
            }
            if( values.hours < 0 ) {
                values.hours = 23;
                values.days -= 1;
            }
            if( values.days < 0 ) {
                para.replaceWith( paraPassed );
                table.remove();
                clearInterval( zoom.theFinalCountdown.loop );
            } else {
                insertTime();
            }
        };
        
        insertTime();
        para.removeAttr('title').after(table);
        
        if( ! para.parents('.registered').size() ) {
	    // Custom Change text request by client, quick and dirty to fill request. Delete second conditional and
	    // uncommented first to go back to normal countdown text. ?s => Push Dev
            // para.text('Time left until ' + ( isEarly ? 'early-bird': 'registration') + ' deadline:');
               para.text('Time left until registration deadline:');
        }
        
        zoom.theFinalCountdown.loop = setInterval( function() {
            updateTime();
        }, 1000 );
    };
    
    zoom.inputDefaults = function() {
        var inputs = $('input[type=text]');
        inputs.each(function() {
            var input = $(this);
            if( ! input.is('[placeholder]') ) {
                var label = $('label[for=' + input.attr('id') + ']');
                input.attr({'placeholder': label.text()});
                label.hide();
            }
            var defaultText = input.attr('placeholder');
            if( ! input.attr('title') ) {
                input.attr({'title': defaultText });
            }
            if( ! $.browser.safari ) {
				if (input.val() == '') input.val(defaultText);
                input.focus(function() {
                    if( input.val() == defaultText ) {
                        input.val('');
                    }
                });
                input.blur(function() {
                    if( input.val() === '' ) {
                        input.val(defaultText);
                    }
                });
            }
        });
        if( ! $.browser.safari ) {
            $('form').each(function() {
                var form = $(this);
                form.submit(function(s) {
                    form.find('input[type=text]').each(function() {
                        var input = $(this);
                        if( input.val() == input.attr('placeholder') ) {
                            input.val('');
                        }
                    });
                    return true;
                });
            });
        }
    };
    
    zoom.registrationForm = function() {
        var form = $('body.register #main form');
        
        if( ! form.size() ) { return; }
        
        var fieldsets = form.find('fieldset.attendee');
        var attendee = $(fieldsets[fieldsets.length-1]);
        
        var add = $('<p class="add"><a href="#add-attendee" title="Add additional attendees">Add additional attendees</a></p>');
        
        attendee.after(add);
        
        var totals = $('<ol><li><strong>Total Attendees:</strong> <span class="count"></span></li><li><strong>Total Cost:</strong> $<span class="total"></span></li></ol>');
        var placeholders = {
            'count': totals.find('span.count'),
            'total': totals.find('span.total')
        };
        var cost = parseInt( form.find('input[name=cost]').val(), 10 );
        var updateTotals = function() {
            var count = form.find('fieldset.attendee').size();
            placeholders.count.text(count);
            placeholders.total.text( count * cost );
			$("#total_cost").val(count * cost);
			$("#attendee_count").val(count);
        };
        updateTotals();
        add.after(totals);
		
		$("a.close").click(function(c) {
			c.preventDefault();
			var attendeeClone = $(this).parent("fieldset.attendee");
			attendeeClone.fadeOut(500, function() {
				attendeeClone.remove();
				resetIndexes(form);
				updateTotals();
			});
		});
		
		resetIndexes = function(form) {
			form.find('fieldset.attendee').each(function(index) {
					if( index === 0 ) { return; }
					$(this).find('legend').text('Attendee ' + ( index + 1 ) + ' Information');
					
					$(this).find("[id^='id_first_name']").attr({ 'id': 'id_first_name[' + index + ']', 'name': 'attendee[' + index + '][first_name]' });
					$(this).find("[for^='id_first_name']").attr({ 'for': 'id_first_name[' + index + ']' });
					
					$(this).find("[id^='id_last_name']").attr({ 'id': 'id_last_name[' + index + ']', 'name': 'attendee[' + index + '][last_name]' });
					$(this).find("[for^='id_last_name']").attr({ 'for': 'id_last_name[' + index + ']' });
					
					$(this).find("[id^='id_company']").attr({ 'id': 'id_company[' + index + ']', 'name': 'attendee[' + index + '][company]' });
					$(this).find("[for^='id_company']").attr({ 'for': 'id_company[' + index + ']' });
					
					$(this).find("[id^='id_title']").attr({ 'id': 'id_title[' + index + ']', 'name': 'attendee[' + index + '][title]' });
					$(this).find("[for^='id_title']").attr({ 'for': 'id_title[' + index + ']' });
				});
		};
        
        add.find('a').click(function(c) {
            c.preventDefault();

            //var attendeeClone = attendee.clone(false);
            var cloneCount = form.find('fieldset.attendee').size();
			
            var attendeeClone = $('<fieldset class="attendee">' +
            '   <legend>Attendee Information</legend>' +
            '	<ol>' +
            '		<li>' +
            '			<label for="id_first_name[' + cloneCount + ']">First Name</label>' +
            '			<input type="text" name="attendee[' + cloneCount + '][first_name]" value="" id="id_first_name[' + cloneCount + ']" />' +
            '		</li>' +
            '		<li>' +
            '			<label for="id_last_name[' + cloneCount + ']">Last Name</label>' +
            '			<input type="text" name="attendee[' + cloneCount + '][last_name]" value="" id="id_last_name[' + cloneCount + ']" />' +
            '		</li>' +
			'		<li>' +
			'			<label for="id_company[' + cloneCount + ']">Company Name</label>' +
			'			<input type="text" name="attendee[' + cloneCount + '][company]" value="' + (($('#id_company\\[' + (cloneCount-1) + '\\]').val() != $('#id_company\\[' + (cloneCount-1) + '\\]').attr('placeholder')) ? $('#id_company\\[' + (cloneCount-1) + '\\]').val() : '') + '" id="id_company[' + cloneCount + ']" />' +
			'		<li>' +
			'			<label for="id_title[' + cloneCount + ']">Job Title</label>' +
			'			<input type="text" name="attendee[' + cloneCount + '][title]" value="" id="id_title[' + cloneCount + ']" />' +
			'		</li>' +
            '   </ol>' +
            '</fieldset>');
			
            attendeeClone.find('input').each(function() {
                var input = $(this);
                if( ! $.browser.safari && ! input.val() ) {
					// console.debug(input.val());
					// console.debug(input.attr('placeholder'));
                    input.val( input.attr('placeholder') );
                }
                input.attr({ 'name': input.attr('name').replace(/0/, cloneCount ) });
            });
            var close = $('<a href="#remove-attendee" class="close" title="Remove this attendee">&times;</a>');
            attendeeClone.append( close ).hide().find('legend').text('Attendee ' + ( cloneCount + 1 ) + ' Information');
            close.click(function(c) {
                c.preventDefault();
                attendeeClone.fadeOut(500, function() {
                    attendeeClone.remove();
                    form.find('fieldset.attendee').each(function(index) {
                        if( index === 0 ) { return; }
						resetIndexes(form);
                        //$(this).find('legend').text('Attendee ' + ( index + 1 ) + ' Information');
                    });
                    updateTotals();
                });
            });
            add.before(attendeeClone);
            zoom.inputDefaults();
            attendeeClone.fadeIn(500, function() {
                updateTotals();
            });
        });
        
        var billingInfo = form.find('fieldset.billing-information');
        var iAmAuthorized = form.find('fieldset.payment-method li.checkbox');
        form.find('input[name=payment_method]').change(function() {
            if( $(this).val() == 'credit-card' && billingInfo.is(':hidden') ) {
                iAmAuthorized.hide();
                billingInfo.slideDown(500);
            } else if ( $(this).val() == 'on-file' && billingInfo.is(':visible') ) {
                iAmAuthorized.show();
                billingInfo.slideUp(500);
            }
        }).removeAttr('checked').filter('[value=on-file]').attr({'checked': 'checked'});
        if( ! form.find('input[value=on-file]').is('[checked]') ) {
            iAmAuthorized.hide();
        }
        billingInfo.hide();
		
		if (zoom.payment_method == 'credit-card') {
			$("#id_payment_method_2").click();
			$("#id_payment_method_2").change();
		}
    };
    
    zoom.slideshow = function() {

        var protos = {
            'wrapper': $('<div class="wrapper"></div>'),
            'frame': $('<div class="frame"></div>')
        };
        
        var rotator = {
            'left': function(wrapper,images) {
                var current = images.filter('img[current]');
                current.removeAttr('current');
                var to = images.eq(images.index(current) + 1).size() ? images.eq(images.index(current) + 1) : images.eq(0);
                var isLast = ( images.index(to) + 1 == images.size() );
                to.attr({'current': 'current'});
                wrapper.animate(
                    {
                        'left': ( 0 - to.position().left ) + 'px'
                    },
                    1000,
                    'easeInOutSine',
                    function() {
                        if( isLast ) {
                            wrapper.css({
                                'left': 0
                            });
                            to.removeAttr('current');
                            images.eq(0).attr({'current':'current'});
                        }
                    }
                );
            },
            'right': function(wrapper,images) {
                var current = images.filter('img[current]');
                current.removeAttr('current');
                var to = images.eq(images.index(current) - 1).size() ? images.eq(images.index(current) - 1) : images.eq(images.size() - 1);
                var isLast = ( images.index(to) === 0 );
                to.attr({'current': 'current'});
                wrapper.animate(
                    {
                        'left': ( 0 - to.position().left ) + 'px'
                    },
                    1000,
                    'easeInOutSine',
                    function() {
                        if( isLast ) {
                            
                            wrapper.css({
                                'left': ( 0 - images.eq( images.size() - 1 ).position().left ) + 'px'
                            });
                            to.removeAttr('current');
                            images.eq(images.size() - 1).attr({'current':'current'});
                        }
                    }
                );
            }
        }
        
        $('.slideshow').each(function(index) {
            var container = $(this);
            var images = container.find('img');
            var frame = protos.frame.clone();
            container.append(frame);
            if( images.size() < 2 ) { return; }
            var wrapper = protos.wrapper.clone();
            images = images.add(images.eq(0).clone());
            wrapper.append(images).appendTo(container);
            var totalWidth = 0;
            images.each(function() {
                totalWidth += $(this).width();
            });
            wrapper.width(totalWidth);
            if( index % 2 ) {
                images.eq(images.size() - 1).attr({'current': 'current'});
                wrapper.css({
                    'left': ( 0 - images.eq(images.size() - 1).position().left ) + 'px'
                })
                setInterval(function(){
                        rotator.right(wrapper,images);
                }, 6000);
            } else {
                images.eq(0).attr({'current': 'current'});
                setInterval(function(){
                        rotator.left(wrapper,images);
                }, 6000);
            }
        });
    };
    
    zoom.truncateSections = function() {
        var separators = $('div[class^=section] hr');
        
        if( ! separators.size() ) { return; }
        
        var protos = {
            'readMore': $('<a href="#read-more" title="Read More">Read&nbsp;More</a>')
        };
        
        var stylesheet = $('<style />');
        stylesheet.text('.scripted-section { overflow: hidden; }');
        $('head link[type=text/css]').eq(0).before(stylesheet);
        
        
        separators.each(function() {
            var separator = $(this);
            var readMore = protos.readMore.clone();
            var secondReadMore = protos.readMore.clone();
            var section = separator.parents('div[class^=section]');
            var prevElem = separator.prev();
            var otherElems = separator.nextAll();
            
            section.addClass('scripted-section');
            
            prevElem.html( prevElem.html() + ' ').append(readMore);
            otherElems.eq(otherElems.size() - 1).after(secondReadMore);
            otherElems = otherElems.add(secondReadMore);
            
            var readMores = readMore.add(secondReadMore);
            
            var origHeight = section.height();
            otherElems.hide();
            var closedHeight = section.height();
            section.addClass('closed');
            
            readMores.click(function(c) {
                c.preventDefault();
                if( section.is('.closed') ) {
                    section.animate(
                        {
                            'height': origHeight
                        },
                        500,
                        'easeInOutSine',
                        function() {
                            otherElems.fadeIn(500, function() {
                                section.removeClass('closed');
                                readMores.addClass('on').html('Show&nbsp;Less').attr({'title': 'Show Less'});
                            });
                        }
                    )
                } else {
                    otherElems.fadeOut(500,
                        function() {
                            section.animate(
                                {
                                    'height': closedHeight
                                },
                                500,
                                'easeInOutSine',
                                function() {
                                    section.addClass('closed');
                                    readMores.removeClass('on').html('Read&nbsp;More').attr({'title': 'Read More'});
                                }
                            );
                        }
                    );
                }
            });
        });
    };
    
})(jQuery);
