/**
* Event Class.
* JavaScript Document
*
*/
var Event = new function(){
            this.counter = 1;
            this.html = '';
            this.unloadFrame = false;
            this.popup = '';
            this.scrollXWin = 0;
            this.scrollYWin = 0;
            this.showAjaxLoader = false;
            this.lightBoxH = '40px';
            this.obj = null;
            this.mTop = 100;
            this.requestTimeOut = null;
            this.requestTimeOutTime = 10000;
            ref = this;

            // AJAX call.
            this.link = function(obj, method, asyn, parameters, elementId, dataType, cache, confirmMsg, openIn, position, reLoad, onComplete, requestUrl){
                    this.isAjax = true;
                    this.requestAddress = '';
                    this.objChild = obj.innerHTML;
                    this.method = method;
                    this.asyn = asyn;
                    this.parameters = parameters;
                    this.elementId = elementId;
                    this.dataType = dataType;
                    this.cache = cache;
                    this.position = position;
                    this.popup = openIn;
                    this.reLoad = reLoad;
                    this.onComplete = onComplete;

                    if(confirmMsg.length > 0){
                        if(!confirm(confirmMsg))
                            return false;
                    }

                    if(typeof(requestUrl)== 'undefined'){
                        this.requestAddress = obj.href;
                    }else{
                        this.requestAddress = requestUrl;
                    }

                    if(typeof(this.popup.type)== 'string'){
                        switch(this.popup.type){
                            case 'lightbox':
                                if(this.obj == obj && (typeof(this.popup.reLoad) == 'undefined' || this.popup.reLoad == 'false' || this.popup.reLoad == false)){
                                    this.isAjax = false;
                                }else{
                                    this.isAjax = true;
                                }
                                this.loadLightbox();
                                this.elementId = 'lb-body';
                                break;
                        }
                        this.showAjaxLoader = false;
                    }else{
                        if(this.obj == obj && (typeof(this.reLoad) == 'undefined' || this.reLoad == 'false' || this.reLoad == false)){
                            this.isAjax = false;
                        }else{
                            this.isAjax = true;
                            /* Processing
                            obj.innerHTML = '<span class="ajax-loader">' + ajaxLoader + '</span>';
                            this.showAjaxLoader = true;*/
                            ref.pageTransistionShow('Loading...');
                        }                        
                    }

                    // Ajax request
                    this.obj = obj;
                    if(this.isAjax)
                        this.ajax();

                    return false;
            }

            this.ajax = function(){
                   ref.loadTimeOut();
                   $.ajax({
                       type: ref.method,
                       url: ref.requestAddress,
                       cache: ref.cache,
                       async: ref.asyn,
                       data: ref.parameters,
                       dataType: ref.dataType,
                       error: function(XMLHttpRequest, textStatus, errorThrown){
                            ref.pageTransistionShow('Request: ' + textStatus + '...Please try again.');
                            clearTimeout(ref.requestTimeOut);
                       },
                       success: function(contents){
                                var jsonRequest = false;

                                clearTimeout(ref.requestTimeOut);
                                if(ref.showAjaxLoader)
                                    ref.obj.innerHTML = ref.objChild;
                                contents = ref._decodeSpecialChar(contents);

                                try{
                                    content = eval('(' + contents + ')');
                                    jsonRequest = true;
                                }catch(e){
                                    jsonRequest = false;
                                }

                                if(typeof(ref.position) == 'undefined')
                                   ref.position = 'INNER';
                                else
                                   ref.position = ref.position.toUpperCase();
                                
                                if(jsonRequest && ref.isArray(ref.elementId)){
                                    for(index=0; index < ref.elementId.length ; index++){
                                        if($('#' + ref.elementId[index]).length > 0){
                                            switch(ref.position){
                                                case 'BEFORE':
                                                    $('#' + ref.elementId[index]).prepend(content[index]);
                                                    break;

                                                case 'AFTER':
                                                    $('#' + ref.elementId[index]).append(content[index]);
                                                    break;

                                                default:
                                                    $('#' + ref.elementId[index]).html(content[index]);
                                            }
                                        }
                                    }
                               }else{
                                   content = contents;
                                   if($('#' + ref.elementId).length > 0 && ref.elementId != ''){
                                       switch(ref.position){
                                            case 'BEFORE':
                                                $('#' + ref.elementId).prepend(contents);
                                                break;

                                            case 'AFTER':
                                                $('#' + ref.elementId).append(contents);
                                                break;

                                            default:
                                                $('#' + ref.elementId).html($(contents));

                                        }
                                   }
                               }

                               if(contents.indexOf('window.location') <= 0)
                                    ref.pageTransistionHide();
                               
                               if(typeof(ref.onComplete) != 'undefined'){
                                    if(ref.isfunctionExists(ref.onComplete)){
                                        ref.cal(ref.onComplete);
                                    }
                               }                               
                       }
                 });
            }

            this.isArray = function(obj) {
                return obj.constructor == Array;
            }

            this.isUrl = function(s) {
                var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
                return regexp.test(s);
            }

            this.isfunctionExists = function(funcName){
                if(typeof funcName == 'string' && eval('typeof ' + funcName) == 'function') {
                   return true;
                }
                return false;
            }

            this.cal = function(funcName){
                eval(funcName);
            }

            // Lightbox
            this.loadLightbox = function(){
                var Width = 700;

                if($('#lightbox').length == 0){
                    this.html = "<table id='lightbox' class='scroll' cellpadding=0 cellspacing=0><tr><td width='25' class='top-left-corner'></td><td class='top-pix'><div id='lb-close'><span style='cursor: pointer;'>&nbsp;</span></div></td><td width='25' class='top-right-corner'></td></tr><tr><td class='left-pix'></td><td bgcolor='#FFF'><div id='lb-body'></div></td><td class='right-pix'></td></tr><tr><td width='25' class='bottom-left-corner'></td><td class='bottom-pix'></td><td width='25' class='bottom-right-corner'></td></tr></table>";
                    $('body').append(this.html);
                    if(!(typeof(this.popup.backlay) != 'undefined' && (this.popup.backlay == false || this.popup.backlay == 'false'))){
                        $('<div id="backlayout"></div>').insertBefore('#lightbox');
                        $('#backlayout').css({width: '100%', height: $(document).height() + 'px', background: '#000', opacity: '0.6', filter: 'alpha(opacity = 60)', zIndex: '9999', position: 'absolute', top: '0px', left: '0px'});
                    }
                }

                // If this is an ajax request, show ajax loader
                if(this.isAjax){
                   /* if(typeof(ajaxLoaderPath) == 'undefined')
                        var ajaxLoaderPath = 'Loading..';*/
                    $('#lb-body').html("<table width='100%'><tr><td height=200 align='center'>"+ajaxLoaderPath+"</td></tr></table>");
                }

                if(typeof(this.popup.scroll) == 'undefined' || this.popup.scroll == 'true' || this.popup.scroll == true)
                    $('#lightbox')[0].className = 'scroll';
                else
                    $('#lightbox')[0].className = 'no-scroll';

                if(typeof(this.popup.width)!= 'undefined')
                        Width = parseInt(this.popup.width);

                if(typeof(this.popup.position)!= 'undefined' && this.popup.position == 'relative'){
                    var offsetValues = $(this.obj).offset();
                    Left = offsetValues.left;
                    Top = offsetValues.top;
                    this.mTop = Top;
                }else{
                    if(typeof(this.popup.top)!= 'undefined'){
                        Top = parseInt(this.popup.top);
                    }
                    else{
                        var scrl = this.getScrollXY();
                        Top = scrl.y + this.mTop;
                    }

                    if(typeof(this.popup.left)!= 'undefined')
                        Left = parseInt(this.popup.left);
                    else
                        Left = Math.ceil(($(document).width() - Width) / 2);
                }

                if(typeof(this.popup.background)!= 'undefined')
                    Background = this.popup.background;
                else
                    Background = 'none';

                $('#lightbox').css({display: 'none', position: 'absolute', zIndex: '10000', width: Width + 'px', height: 'auto', left: Left + 'px', top: Top + 'px'});
                $('#lb-body').css({background: '#FFF'});
                $('#lb-close').css({textAlign: 'right', color: 'red', fontSize: '1.2em', fontWeight: 'bold'});
                if(!(typeof(this.popup.backlay) != 'undefined' && (this.popup.backlay == false || this.popup.backlay == 'false')))
                    $('#backlayout').css({display: 'block', filter: 'alpha(opacity = 60)'});
                $('#lightbox').fadeIn();
                $('#lb-close span').click(function(){
                    $('#lightbox').fadeOut('slow');
                    if(!(typeof(ref.popup.backlay) != 'undefined' && (ref.popup.backlay == false || ref.popup.backlay == 'false')))
                        $('#backlayout').fadeOut('slow');

                    // Lightbox on close event
                    if(typeof(ref.popup.onClose) != 'undefined'){
                        if(ref.isfunctionExists(ref.popup.onClose)){
                            ref.cal(ref.popup.onClose);
                        }
                    }
                    // unbind the click event
                    $(this).unbind( "click" );
                });
            }

            // Auto close a light box while redirecting from a lightbox
            this.autoCloseLightbox = function(){
                if($('#lightbox').length > 0)
                    $('#lightbox').hide();
                if($('#backlayout').length > 0)
                $('#backlayout').hide();
            }

            this.pageTransistionShow = function(msg){
                if($('#transmsg').length > 0){
                    $('#transmsg').text(msg);
                    $('#transmsg').show();
                }else
                    $('body').append($("<div id='transmsg' style='position: absolute; top: 0;left: 47%; padding:5px;-moz-border-radius:0 0 5px 5px;background:#ffe91d;font-weight:bold;color:#000000;'>"+msg+"</div>"));
            }

            this.pageTransistionHide = function(){
                if($('#transmsg').length > 0){
                    $('#transmsg').hide();
                    $('#transmsg').text('');
                }
            }

            this.lightbox = function(){
                var h = $('#lb-body').css('height');
                var w = $('#lb-body').css('width');
                $('#lb-body').css({height: this.lightBoxH});
                this.lightBoxH = h;
                $('#lb-body').hide();
                this.animateZoom(h, w, $('#lb-body'));
            }

            // AUTO RESIZE ANIMATION
            this.animateZoom = function(zheight, zwidth, box){
                $(box).animate({ width: zwidth, height: zheight}, 1000,'',function(){
                        $(this).css({background: 'none', border: '0'});
                });
            }

            // Add more nodes/elements
            this.add = function(obj, count){
                if(this.counter <= count){
                    this.counter++;
                    var currentTime = new Date();
                    var id = currentTime.getTime();
                    $(obj).parent().append('<div id="'+id+'"></div>');
                    var inputClone = $(obj).prev().prev().prev().clone(true);
                    $('#'+id).append(inputClone);
                    $('#'+id).append('<input type="hidden" value="'+this.counter+'" name="uid"/><span id="'+id+'_process"></span><a href="" class="remove" onclick="javascript: return Event.remove(this);">Remove</a>');
                    $('#'+id).append('<br/><span id="'+id+'_update"></span>');
                }

                return false;
            }

            // Remove a node/element
            this.remove = function(obj){
                $(obj).parent().remove();
                this.counter--;
                return false;
            }

            // Upload a file using iframe.
            this.upload = function(obj, position){
                var removeIframe = false;
                // Create a new iframe.
                var iframe = document.createElement('iframe');
                iframe.name = 'upload';
                iframe.style.display = 'none';

                var ajaxUpload = document.createElement('input');
                ajaxUpload.name = 'ajaxUpload';

                if($(obj).next().attr('name') == 'uid'){
                    ajaxUpload.value = $(obj).next().val();
                }else{
                    ajaxUpload.value = '1';
                }

                ajaxUpload.type = 'hidden';

              //  var uploadFieldClone = obj.cloneNode(true);
                var uploadFieldClone = $(obj).clone(true);

                // Create a new file upload form element.
                var formField = document.createElement('form');
                formField.name = 'upload_form';
                formField.method = 'post';
                if(obj.form.action.length == 0){
                    formField.action = window.location;
                }else{
                    formField.action = obj.form.action;
                }
                formField.enctype = 'multipart/form-data';

                // Append the file input field object last of the form.
                uploadFieldClone.insertAfter($(obj));
                formField.appendChild($(obj)[0]);
                formField.appendChild(ajaxUpload);

                // Append the iframe object last of the body contents.
                document.body.appendChild(iframe);

                // Append the form object last of the iframe body contents.
                iframe.contentWindow.document.body.appendChild(formField);

                // Auto submit the form.
                uploadFieldClone.next().next().html('processing...');

                iframe.contentWindow.document.forms[0].submit();

                // Disable Submit button until processing completes.
                uploadFieldClone.parents('form').eq(0).find('input:submit, input:image').eq(0).attr('disabled', 'disabled');

                iframe.onload = function(){
                    uploadFieldClone.next().next().html('');
                    var id = String(uploadFieldClone.next().next().attr('id'));
                    var updateId = id.replace("process", "update");

                    if(typeof(position) == 'undefined')
                       position = 'INNER';
                    else
                       position = position.toUpperCase();

                   switch(position){
                        case 'BEFORE':
                            $('#' + updateId).prepend(iframe.contentWindow.document.body.innerHTML);
                            break;

                        case 'AFTER':
                            $('#' + updateId).append(iframe.contentWindow.document.body.innerHTML);
                            break;

                        default:
                            $('#' + updateId).html(iframe.contentWindow.document.body.innerHTML);

                    }
                    removeIframe = true;
                    // Enable Submit button upon complete processing.
                    uploadFieldClone.parents('form').eq(0).find('input:submit, input:image').eq(0).removeAttr('disabled');
                }

                // Remove iframe
                var interval = setInterval(function(){
                    if(removeIframe){
                        iframe.parentNode.removeChild(iframe);
                        if(ajaxUpload.value > 1){
                            uploadFieldClone.val('');
                        }else{
                           uploadFieldClone.val('');
                        }
                        clearInterval(interval);
                    }
                }, 200);
            }


            // Submit a form.
            this.submitForm = function(obj, method, asyn, parameters, elementId, dataType, cache, confirmMsg, openIn, position, reLoad, onComplete){
                    if(typeof(formValidationErrors) == 'undefined' || !formValidationErrors){
                        var submitElem = $(obj).find('input[type="submit"], input[type="image"]');
                        var submElem = '&' + submitElem.attr('name') + '=' + escape(submitElem.val());
                        var params = $(obj).serialize();
                        parameters = params + submElem +  parameters;
                        this.link($(obj).find('.load-ajax').eq(0)[0], method, asyn, parameters, elementId, dataType, cache, confirmMsg, openIn, position, reLoad, onComplete, obj.action);
                    }
                    return false;
            }

            this._decodeSpecialChar = function(contents){

                contents = contents.replace(/ /g, ' ');
                contents = contents.replace(/&ldquo;|&rdquo;/g, '"');
                contents = contents.replace(/&ndash;/g, '-');

                return contents;
            }

            // Scroll window
            this.scrollWin = function(){
                var scrl = this.getScrollXY();
                y = scrl.y + ref.mTop;
                if($('#lightbox').length > 0 && $('#lightbox').hasClass('scroll')){
                    $('#lightbox').animate({ top: y + 'px'}, 150);
                }else{
                    if(y < parseInt($('#lightbox').css('top'))){
                        $('#lightbox').animate({ top: y + 'px'}, 150);
                    }
                }                
            }

            this.getScrollXY = function() {
                  var scrOfX = 0, scrOfY = 0;
                  if( typeof( window.pageYOffset ) == 'number' ) {
                    //Netscape compliant
                    scrOfY = window.pageYOffset;
                    scrOfX = window.pageXOffset;
                  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
                    //DOM compliant
                    scrOfY = document.body.scrollTop;
                    scrOfX = document.body.scrollLeft;
                  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
                    //IE6 standards compliant mode
                    scrOfY = document.documentElement.scrollTop;
                    scrOfX = document.documentElement.scrollLeft;
                  }
                  return { x: scrOfX, y: scrOfY };
            }

            this.resetCounter = function(){
                this.counter = 1;
            }

            this.checkAll = function(obj, clas){
                if(obj.checked)
                    $('.' + clas).attr('checked', 'checked');
                else
                    $('.' + clas).removeAttr('checked');
            }

            this.loadTimeOut = function(){
                ref.requestTimeOut = window.setTimeout(function(){ref.pageTransistionShow('Page loading is taking time. Please be patient.');}, ref.requestTimeOutTime);
            }

            this.flash = function(msg){
                if($('#flashmsg').length > 0){
                    $('#flashmsg').text(msg);
                   
                }else
                    $('body').append($("<div id='flashmsg' style='text-shadow:0 1px 2px #666; text-align: center; display: none; position: fixed; top: 0;left: 0; width:100%; background:#FFF; opacity:0.9; filter:alpha(opacity=90); color:#000000;'>"+msg+"</div>"));

                $('#flashmsg').slideDown('slow');
                setTimeout(function(){$('#flashmsg').slideUp('slow');}, 5000);
            }
    }

$(document).ready(function(){    
    $(window).scroll(function(){
        Event.scrollWin();
    });
});

window.onbeforeunload  = function(){
    Event.loadTimeOut();    
    Event.pageTransistionShow('Loading...');    
}
