/* 
 * Handle forms submission via AJAX
 * 
 */

var waitDialogShown = false;
var useTimerBeforeShowWaitDialog = true;
var waitDialogTimeout = 50;
var waitDialogTimer = false;

function newAjax(){
    var xmlhttp=false;
    try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
    try {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
    xmlhttp = false;
    }
    }

    if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
    xmlhttp = new XMLHttpRequest();
    }
    return xmlhttp;
}

function sendForm(url, formId, responseElem){
        onRequestStart();
        valid = walkTroughForm(formId);
//        alert(valid);
        if(valid == true){
            var form = document.getElementById(formId);
            var formLength = form.elements.length;
            var formString = "";
            var sepFields;
            sepFields = "";
            for (var i=0; i < formLength;i++) {
                formString += sepFields+form.elements[i].name+'='+encodeURI(form.elements[i].value);
                sepFields="&";
            }
            rq=newAjax();
            rq.open("POST", url, true);
            rq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
            rq.send(formString);
            rq.onreadystatechange = function() {
                  if (rq.readyState == 4 && (rq.status == 200 || window.location.href.indexOf ("http") == - 1)){
                        document.getElementById(responseElem).innerHTML = rq.responseText;
                  }else{
                      onRequestEnd();
                      cleanForm(formId);
                  }
            }
        }else{
            onRequestEnd();
        }
}

function showWaitDialog() {
    //avoid attempt to show it if it is already shown
    if (!waitDialogShown) {
        showModalPanel(
        'wait-dialog',
        400,
        'Su Petición está siendo Procesada. Gracias!',
        close = false);
        waitDialogShown = true;
    }
}

function onRequestStart() {
    if (useTimerBeforeShowWaitDialog) {
        waitDialogTimer = setTimeout("showWaitDialog();", waitDialogTimeout);
    } else {
        showWaitDialog();
    }
}
function onRequestEnd() {
    if (waitDialogShown) {
        closeModalPanel('wait-dialog', 'Su mensaje ha sido enviado. Gracias!');
        waitDialogShown = false;
    } else{
         if(useTimerBeforeShowWaitDialog && waitDialogTimer) {
            clearTimeout(waitDialogTimer);
        }
    }
}

function showModalPanel(modalId, width, msg, close){
    var popID = modalId; //Get Popup Name
    $('#'+modalId+' .modal_img').show();
    $('#'+modalId+' .modal_img').css({'float' : 'left'})
    $('#'+modalId+' .modal_msg').text(msg);
    $('#'+modalId+' .modal_msg').css({'text-align' : 'none'})
    $('#'+modalId+' .modal_msg').css({'width' : 'auto'})
    var popURL = $(this).attr('href'); //Get Popup href to define size

    //Pull Query & Variables from href URL
    var popWidth = width; //Gets the first query string value

    if(close == true){
        //Fade in the Popup and add close button
        $('#' + popID).fadeIn().css({'width': Number( popWidth )}).
        prepend('<a href="#" class="close" onclick="closeModalPanel()"><img src="close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');
    }else{
        $('#' + popID).fadeIn().css({'width': Number( popWidth )});
    }
    

    //Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
    var popMargTop = ($('#' + popID).height() + 80) / 2;
    var popMargLeft = ($('#' + popID).width() + 80) / 2;

    //Apply Margin to Popup
    $('#' + popID).css({
        'margin-top' : -popMargTop,
        'margin-left' : -popMargLeft
    });

    //Fade in Background
    $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
    $('#fade').css({'filter' : 'alpha(opacity=30)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies

    return false;
}

function closeModalPanel(modalId, msg){
        $('#'+modalId+' .modal_img').hide();
        $('#'+modalId+' .modal_msg').text(msg);
        $('#'+modalId+' .modal_msg').css({'width' : '95%'})
        $('#'+modalId+' .modal_msg').css({'text-align' : 'center'})
        $('#fade, #'+modalId).delay(3000).fadeOut(function() {
            $('#fade, a.close').remove();  //fade them both out
        });
        return false;
}

$(document).ready(function(){
    //Tooltips
    $('.form_table_cell').hover(function(){
        tip = $(this).find('.tip');
        tip.fadeIn(); //Show tooltip
    }, function() {
        tip.hide(); //Hide tooltip
    }).mousemove(function(e) {
        var mousex = e.pageX; //Get X coodrinates
        var mousey = e.pageY; //Get Y coordinates
//        alert(mousex+' - '+mousey);
        var tipWidth = tip.width(); //Find width of tooltip
        var tipHeight = tip.height(); //Find height of tooltip
//        alert(tipWidth+' - '+tipHeight);
//        alert($(window).width()+' - '+$(window).height());

        //Distance of element from the right edge of viewport
        var tipVisX = $(window).width() - (mousex + tipWidth);
        //Distance of element from the bottom of viewport
        var tipVisY = $(window).height() - (mousey + tipHeight);

        var tipX = (mousex + tipWidth) - mousex;
        var tipY = (mousey + tipHeight) - mousey;

        if ( tipVisX < 20 ) { //If tooltip exceeds the X coordinate of viewport
            mousex = e.pageX - tipWidth - 20;
        }if ( tipVisY < 20 ) { //If tooltip exceeds the Y coordinate of viewport
            mousey = e.pageY - tipHeight - 20;
        }
        //Absolute position the tooltip according to mouse position
        tip.css({'margin-top' : 10, 'margin-left': 250});
    });
});

//$(document).ready(function() {
//    //When you click on a link with class of poplight and the href starts with a #
//    $('a.poplight[href^=#]').click(function() {
//        var popID = $(this).attr('rel'); //Get Popup Name
//        var popURL = $(this).attr('href'); //Get Popup href to define size
//
//        //Pull Query & Variables from href URL
//        var query= popURL.split('?');
//        var dim= query[1].split('&');
//        var popWidth = dim[0].split('=')[1]; //Gets the first query string value
//
//        //Fade in the Popup and add close button
//        $('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<a href="#" class="close"><img src="close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');
//
//        //Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
//        var popMargTop = ($('#' + popID).height() + 80) / 2;
//        var popMargLeft = ($('#' + popID).width() + 80) / 2;
//
//        //Apply Margin to Popup
//        $('#' + popID).css({
//            'margin-top' : -popMargTop,
//            'margin-left' : -popMargLeft
//        });
//
//        //Fade in Background
//        $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
//        $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies
//
//        return false;
//    });
//
//    //Close Popups and Fade Layer
//    $('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
//        $('#fade , .popup_block').fadeOut(function() {
//            $('#fade, a.close').remove();  //fade them both out
//        });
//        return false;
//    });
//});





//function objetus(file) {
//    xmlhttp=false;
//    this.AjaxFailedAlert = "Su navegador no soporta las funciónalidades de este sitio
//		 y podria experimentarlo de forma diferente a la que fue pensada.
//		 Por favor habilite javascript en su navegador para verlo normalmente.\n";
//    this.requestFile = file;
//    this.encodeURIString = true;
//    this.execute = false;
//    if (window.XMLHttpRequest) {
//        this.xmlhttp = new XMLHttpRequest();
//        if (this.xmlhttp.overrideMimeType) {
//            this.xmlhttp.overrideMimeType('text/xml');
//        }
//    }
//    else if (window.ActiveXObject) { // IE
//        try {
//            this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
//        }catch (e) {
//            try {
//                this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
//            } catch (e) {
//                this.xmlhttp = null;
//            }
//        }
//        if (!this.xmlhttp && typeof XMLHttpRequest!='undefined') {
//            this.xmlhttp = new XMLHttpRequest();
//            if (!this.xmlhttp){
//                this.failed = true;
//            }
//        }
//    }
//    return this.xmlhttp ;
//}


//<script type="text/javascript">
//		function ajaxRequestContainsErrors() {
//			return document.getElementById("maximumSeverity").value == "2";
//		}
//		function closeModalPanel(panelId) {
//			if (!ajaxRequestContainsErrors()) Richfaces.hideModalPanel(panelId);
//		}
//
//
//		var waitDialogShown = false;
//		var useTimerBeforeShowWaitDialog = true;
//		var waitDialogTimeout = 50;
//		var waitDialogTimer = false;
//
//		function showWaitDialog() {
//		    //avoid attempt to show it if it is already shown
//		    if (!waitDialogShown) {
//		        Richfaces.showModalPanel('wait-dialog');
//		        waitDialogShown = true;
//		    }
//		}
//
//		function onRequestStart(formId, lenght) {
//		    if (useTimerBeforeShowWaitDialog) {
//		        waitDialogTimer = setTimeout("showWaitDialog();", waitDialogTimeout);
//		    } else {
//		        showWaitDialog();
//		    }
//		}
//		function onRequestEnd(formId, lenght, validateEntireForm) {
//		    if (waitDialogShown) {
//		        Richfaces.hideModalPanel('wait-dialog');
//		        waitDialogShown = false;
//		    } else if (useTimerBeforeShowWaitDialog &amp;&amp; waitDialogTimer) {
//		        clearTimeout(waitDialogTimer);
//		    }
//		    if(formId != null){
//				if(validateEntireForm == true){
//					recorrerForm(formId, lenght);
//				}
//			}
//		}
//
//		function onRequestEndForTable(tableId, columns) {
//		    if (waitDialogShown) {
//		        Richfaces.hideModalPanel('wait-dialog');
//		        waitDialogShown = false;
//		    } else if (useTimerBeforeShowWaitDialog &amp;&amp; waitDialogTimer) {
//		        clearTimeout(waitDialogTimer);
//		    }
//		    if(tableId != null){
//				//alert(msgSize);
//				//if(msgSize == 0){
//					recorrerTabla(tableId, columns);
//				//}
//			}
//		}
//   </script>



