// AT Lightbox.js - A jQuery Plugin
// Version 1.1
// Author - Andy Tennison / http://www.tennisons.com

(function($) {
    // global action
    $(document).ready(function () {
        $('body').append('<div id="bg2"></div>');

        $('form:first').append('<div id="bg"></div><div id="lbTemp" class="lbForm"></div>');

        $('form:first').append(
		    '<div id="lb" class="lbForm">'
			    + '<a id="lbClose" href="#">Close<span>&nbsp;</span></a>'
			    + '<span class="tl"></span><span class="tr"></span><span class="bl"></span><span class="br"></span>'
			    + '<span class="t"></span><span class="b"></span><span class="l"></span><span class="r"></span>'
		    + '</div>'
	    );
    });

    //////////////////////////////////////////////////////////////////////////////
    // for each instance of the lightbox

    $.fn.ATlightbox = function(options) {
		
        var opts = $.extend({}, $.fn.ATlightbox.defaults, options);

        // global VARs
        var $c = $('#lbClose'), 	// close button
			$lb = $('#lb'), 		// lightbox
			$bg2 = $('#bg2'), 	    // background mask
			$bg = $('#bg'), 		// background mask
			$temp = $('#lbTemp'),   // temporary container to load ajax content into
			originalForm,           // used to hold content of original form when form is opened
			originalViewState = $('#__VIEWSTATE').val();

        // set generic lightbox css
        $bg.css({ opacity: opts.bgOpacity });
        $bg2.css({ opacity: opts.bgOpacity });
        $lb.css({ 'background-color': opts.lbColor });


        ///////////////////////////////////////////////////////////////////////////////			
        // EACH //
        return this.each(function(i) {
            debug(i + ' - ' + $(this).text());

            var formStateTitle = 'form not complete, do you want to close it?'; // default form close warning
			var $a = $(this); 			// link that is clicked

            var tempW, tempH, type, modForm, fieldID, formState, newContent, topLimit, state = 0;

            var lbDetails = new Object;
            lbDetails.link = $(this);
            lbDetails.timer = 0;
            lbDetails.close = 0;

            /////////////////////////////////////////////////////////////////////////////
            // set basic click actions
            // click BG closes lightbox

            $('#lbClose,#bg,#bg2').click(function(e) {
                e.preventDefault();
                if (lbDetails.close === 1) {
                    closeLB(lbDetails);
                }
            });

            // click link
            lbDetails.link.click(function(e) {
                e.preventDefault();
                lbDetails.href = $a.attr('href');
                state += 1;
                debug('state='+state)
                openLB(lbDetails);
                getContent();
            }); // END link.click

            function getContent() {
                if (lbDetails.href.slice(0, 1) === '#' && lbDetails.link.hasClass(opts.localForm)) {
                    newContent = localCall(lbDetails);
                    if(state == 1)originalForm = newContent.clone().html();

                    lbDetails.formState = newContent.find('input[name=formState]').attr('value');
                    lbDetails.formStateTitle = newContent.find('input[name=formState]').attr('alt');
                    callComplete(newContent)

                } else if (lbDetails.href.match('.aspx')) {
                    lbDetails.callComplete = function(newContent) {
                        callComplete(newContent)
                    };
                    newContent = ajaxCall(lbDetails);
                } else {
                    newContent = false;
                };
            } // END getContent


            function callComplete(newContent) {
                if (newContent === false) {
                    closeLB();
                    debug('lightbox closing due to problem')
                } else {
                    newContent.appendTo($temp);

                    // animations
                    var s = getSize(lbDetails);
                    lbDetails.type = s[0];
                    lbDetails.width = s[1];
                    lbDetails.height = s[2];

                    checkBG(lbDetails);
                    lbDetails.callComplete = function(newContent) {
                        checkType()
                    };
                    animateLB(lbDetails);
                    setTop(lbDetails);


                    function checkType() {

                        if (lbDetails.type === 'video') loadVideo(lbDetails);
                        if (lbDetails.type === 'image') prevNext();
                        if (lbDetails.type === 'form') {
							//$('#lb fieldset').ATform();
                            detectPostback()
                            wordCount(lbDetails)
                        };
                    }
                }
            }; // END callComplete


            // if gallery is loaded prevnext images on click
            function prevNext() {
                $lb.find('#lbNext, #lbPrev').click(function(e) {
                    e.preventDefault();
                    lbDetails.href = $(this).attr('href');
                    $lb.find(opts.contentMarker).fadeOut(300, function() {
                        $(this).remove();
                        $lb.addClass('loading');
                        getContent();
                    })
                })
            };

            // if form detects post back to refresh content
            function detectPostback() {
				$lb.find('input[type=submit]').click(function(e) {
					e.preventDefault();
					var submitButton = $(this);
					activatePostback(submitButton);
                })
            }; // END detectPostback

            // form posts - ajax call on form
            function activatePostback(submitButton) {
                var form = $('form:first');
                var method = form.attr('method');
                var action = form.attr('action');

                var serializedFrom = form.serialize() + '&' + submitButton.attr('name') + '=' + method;
                debug(serializedFrom)

                // submit form
                $.ajax({
                    type: method,
                    url: action,
                    data: serializedFrom,
                    success: function(html) {
                        // load new content
                        var newHTML = $(html).find(lbDetails.href);
						var iEval = $(html).find('input#__EVENTVALIDATION').val();
						var iView = $(html).find('input#__VIEWSTATE').val();
						$('input#__EVENTVALIDATION','#form1').val(iEval);
						$('input#__VIEWSTATE','#form1').val(iView);
                        $('#lbMarker').before(newHTML).end();
                        $('#lbMarker').remove();

                        // hide lighbox content and reload
                        $lb.find(lbDetails.href).fadeOut(300, function() {
                            $(this).remove();
                            $lb.addClass('loading');
                            getContent();
                        })
                    } // END success
                })// END ajax
            }; // END activatePostback



        }); // END this.each


        ///////////////////////////////////////////////////////////////////////////////			
        // FUNCTIONS //

        // close lightbox
        function closeLB(l) {
            var c = true;
            c = confirmClose(l)
            debug(c)

            if (c === true) {
                l.close = 0;
                $(window).unbind('scroll');
                if (l.type === 'form') {
                    debug(l.href)
                    debug($('#__VIEWSTATE').val())
                    var $moveContent = $lb.find(l.href).clone();
                    
                    var newHTML, newVS, newEV;

                    function sortData(data){
                        newHTML = $(data).find(l.href);
                        newVS = $(data).find('#__VIEWSTATE').val();
                        newEV = $(data).find('#__EVENTVALIDATION').val();
                        debug(newVS)
                        updatePage();
                    }
                    
                    var url = window.location.href;
                    $.get(url, sortData)
                    
                    function updatePage(){
                        $('#__VIEWSTATE').val(newVS);
                        $('#__EVENTVALIDATION').val(newEV);
                        $('#lbMarker').before(newHTML);
                        $('#lbMarker').remove();
                    }
                    
                    //debug('original form='+originalForm)
                    
                    //$lb.find(l.href).remove();
                    //$moveContent.removeAttr('style');
                    //$moveContent.html(originalForm);

        			//$('#__VIEWSTATE').val(originalViewState);
        
                    //$('#lbMarker').before($moveContent);
                    //$('#lbMarker').remove();
                };
                $bg.fadeOut(200);
                $bg2.fadeOut(200);
                $lb
					.fadeOut(200, function() { $lb.find(opts.contentMarker).remove() })
					.css({ display: 'none', 'marginLeft': -50, width: 100, 'min-height': 90, height: 'auto' })
					.addClass('loading');

                return formState = '';
            };
        };

        // uses hidden input name=formState to set if field is acive
        function confirmClose(l) {
            if (l.type === 'form' && l.formState === 'active') {
                if (confirm(l.formStateTitle)) {
                    return true;
                } else {
                    return false;
                };
            } else {
                return true;
            }
        };

        // open lightbox
        function openLB(l) {
            l.close = 1;
            $bg.css({ height: $(document).height() });
            $bg2.css({ width: $('body').width(), height: $(document).height() });
            $bg.fadeIn(200);
            $bg2.fadeIn(200);
            $lb.addClass('loading').css({ top: $().scrollTop() + opts.topOffset }).fadeIn(200);
        };

        // local call
        function localCall(l) {
            var $thisContent = $('#content').find(l.href);
            $thisContent.after('<input type="hidden" id="lbMarker" />');
            return $thisContent;
        };

        // calls ajax
        function ajaxCall(l) {
            debug('ajax called')

            $.ajax({
                url: l.href,
                success: function(html) {
                    if ($(html).find(opts.contentMarker).length) {
                        var $thisContent = $(html).find(opts.contentMarker)
                        l.callComplete($thisContent);
                        return $thisContent
                    } else {
                        debug('error: failed during ajax call due to no class=lbcontent in loaded content')
                        return false;
                    }
                },
                error: function(data) {
                    debug('error: failed during ajax due to ajax ERROR being fired');
                    return false;
                }
            })
        };

        // checks the type of content and sets the appropriate size
        function getSize() {
            var W, H, T;
            if ($temp.find('.mod_gallery').length) {
                debug('gallery found');
                W = opts.galleryWidth;
                H = $temp.height();
                T = 'image'
            } else if ($temp.find('.mod_video').length) {
                debug('video found');
                W = opts.videoWidth;
                H = $temp.height();
                T = 'video'
            } else if ($temp.find('.mod_form').length) {
                debug('form found');
                W = opts.formWidth;
                H = $temp.height();
                T = 'form'
            } else {
                T = null;
                W = null;
                H = null;
            };
            return [T, W, H]
        };

        // checks if the content is too long for the page
        function checkBG(l) {
            if ((l.height + opts.topOffset + $().scrollTop()) >= $('body').height()) {
                var H = (l.height + opts.topOffset + $().scrollTop() + 30);
                $bg.height(H);
                $bg2.height(H)
            }
        };

        // animates the size change of the box and fades in the content
        function animateLB(l) {
            if ($lb.width() != l.width && $lb.height() != l.height) {
                $lb.animate({ 'marginLeft': -l.width / 2, 'width': l.width, 'height': l.height }, 350)
            } else if ($lb.width() != l.width || $lb.height() != l.height) {
                if ($lb.width() != l.width) {
                    $lb.animate({ 'marginLeft': -l.width / 2, 'width': l.width }, 350)
                } else if ($lb.height() != l.height) {
                    $lb.animate({ 'height': l.height }, 350)
                };
            };

            $lb.animate({ 'delay': 1 }, 350, function() {
                $temp.children().appendTo($lb);
                $lb.find(opts.contentMarker).fadeIn(500).end().removeClass('loading');
                l.callComplete();
            });
        };

        // if flash is loaded, load video - global function set in functions.js
        function loadVideo(l) {
			runFlash(0,$lb.find('.flashHolder'))
        };

        // if the window is smaller than the screen keep centered
        function setTop(l) {
            $(window).unbind('scroll');
            var lbH = l.height + opts.topOffset,
                wH = $(window).height(),
                t,
                scrollDir;

            topLimit = $().scrollTop();


            l.timer = 0;

            // if lightbox is small keep centered when scrolled
            $(window).scroll(function() {
                if (lbH + 80 < wH && !l.timer) {
                    l.timer = 1;
                    scrollDir = 'both';
                    timedCount(scrollDir);
                    debug('scroll - small, ' + topLimit)
                } else if (lbH + 40 >= wH && !l.timer && topLimit > $().scrollTop()) {
                    l.timer = 1;
                    scrollDir = 'up';
                    timedCount(scrollDir);
                    debug('scroll - large, ' + topLimit)
                }
            });


            function timedCount(dir) {
                debug('scroll - timed count called')
                var topInitial = $().scrollTop();

                t = setTimeout(function() {
                    if (topInitial === $().scrollTop()) {
                        // if after x secs the current scroll position = initial scroll position animate
                        if (dir === 'up' && topInitial < topLimit || dir === 'both') {
                            $lb.animate({ top: (opts.topOffset + $().scrollTop()) }, 500)//{duration:500, easing:easeOutQuad}
                            topLimit = $().scrollTop()
                        };

                        l.timer = 0;
                        debug('scroll - finish')

                    } else {
                        // else loop
                        timedCount(dir, topLimit)
                    }
                }, 400)
            };
        } // END setTop

		// detects wordcount on textareas and limits characters types + feedback
        function wordCount() {
            debug('wordCount running')
            $('textarea').each(function() {
				var txt = {};
				txt.box = $(this);
                txt.text = $(this).val()
                txt.length = txt.text.length;
                txt.max = opts.textareaLength;
				
				txt.box.after('<span class="chars">Characters left:</span>');
				txt.msg = txt.box.next('span.chars');
				
                txt.msg.html('Characters left: ' + (txt.max - length) + ' / ' + txt.max);
                
				// bind on key up event
                txt.box.keyup(function() {
                    if (txt.box.val().length > txt.max) {
                        txt.box.val($(this).val().substr(0, max));
                    }
                    // get new length of characters
                    var new_length = txt.box.val().length;
                    debug('keyup' + new_length)
                    txt.msg.html('Characters left: ' + (txt.max - new_length) + ' / ' + txt.max);
                });
            });
        }

    }; // end plugin ATlightbox

    // private function
    function debug(txt) {
        if (window.console && window.console.log)
            window.console.log('debug: ' + txt);
    }

    $.fn.ATlightbox.defaults = {
        innerContent: '',
        contentMarker: '.lbContent', // class to show content that is copied in AJAX
        topOffset: 20, 		// lightbox distance from top of screen
        galleryWidth: 708, 	// lightbox width
        videoWidth: 610, 		// lightbox width
        formWidth: 470, 		// lightbox width
        lbColor: '#000000', 	// lightbox background-color
        bgOpacity: 0.7, 		// opacity of background mask
        localForm: 'form',		// class for local form
        textareaLength: 200     // max length for all textareas
    };

})(jQuery);// end of closure

