// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// gives error as jquery loads up after -- we have $jq = jQuery.noConflict in assets include
/*
try {
jQuery.noConflict();
} catch(e) {};
*/

//function to show credit profile
function show_credit_profile() {
        new Popup('credit_profile',null,{position:'310,460',effect:'fade'});
        $('credit_profile').popup.show();
}

//function to show loan summary
function show_right_popup() {
        new Popup('right_popup',null,{position:'500,400',effect:'fade'});
        $('right_popup').popup.show();
}


var school = '';
//Set Loan School Detail -> school_id
function setSchoolID(element, selectedElement){
    $('loan_school_detail_school_id').value = (selectedElement.id);
        school = (selectedElement.id);
        new Ajax.Request('/schools/confirm_school_info', {asynchronous:true, evalScripts:true, parameters:'school_id=' + school});
}

// Get the school Name - pass the field to read - not sure where this is useful
//var userSchool = '';
//function getSchoolID(fieldName){
//      userSchool = $F(fieldName);
//}

// REAL bad function name
//function auto_complete_on_select1(element, selectedElement){
//    $('user_school_school_id').value =(selectedElement.id);
//      userSchool = (selectedElement.id);
//
//      new Ajax.Request('/account/confirm_school_info', {asynchronous:true, evalScripts:true, parameters:'school_id=' + userSchool});
//}

function toggleEmployment(){
        var i = $('loan_school_detail_enrollment_status_id').selectedIndex;
    var t = $('loan_school_detail_enrollment_status_id').options[i].text.toLowerCase();
    if(t == "full time" || t == ""){
        $('listing_employment').hide();
    }else{
        $('listing_employment').show();
    }
}

function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }

    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}


function calculateLoanAmount(){
        var tu, rm, bk, br, tr, ot;
        if(isNaN($F('loan_list_tution_fees')) || $F('loan_list_tution_fees') == ""){
                tu = 0;
                $('loan_list_tution_fees').value = 0;
        }else{
                tu = parseFloat($F('loan_list_tution_fees'));
        }

        if(isNaN($F('loan_list_room_board')) || $F('loan_list_room_board') == ""){
                rm = 0;
                $('loan_list_room_board').value = 0;
        }else{
                rm = parseFloat($F('loan_list_room_board'));
        }

        if(isNaN($F('loan_list_health_insurance_fees')) || $F('loan_list_health_insurance_fees') == ""){
                br = 0;
                $('loan_list_health_insurance_fees').value = 0;
        }else{
                br = parseFloat($F('loan_list_health_insurance_fees'));
        }

        if(isNaN($F('loan_list_books_supplies')) || $F('loan_list_books_supplies') == ""){
                bk = 0;
                $('loan_list_books_supplies').value = 0;
        }else{
                bk = parseFloat($F('loan_list_books_supplies'));
        }

        if(isNaN($F('loan_list_transportation')) || $F('loan_list_transportation') == ""){
                tr = 0;
                $('loan_list_transportation').value = 0;
        }else{
                tr = parseFloat($F('loan_list_transportation'));
        }

        if(isNaN($F('loan_list_miscellaneous_personal')) || $F('loan_list_miscellaneous_personal') == ""){
                ot = 0;
                $('loan_list_miscellaneous_personal').value = 0;
        }else{
                ot = parseFloat($F('loan_list_miscellaneous_personal'));
        }

        //$('loan_amount').value = (tu + rm + bk + br + tr + ot);
        $('loan_list_requested_amount').value = (tu + rm + bk + br + tr + ot);
        if($F('loan_list_requested_amount') <= 7500){
                $('loan_list_term').value = "10";
        }
         else if ($F('loan_list_requested_amount') > 7500 && $F('loan_list_requested_amount') <= 10000){
                $('loan_list_term').value = "15";
        }
        else {
                $('loan_list_term').value = "20";
        }
}

// drawPercentBar()
  // Written by Matthew Harvey (matt AT unlikelywords DOT com)
  // (http://www.unlikelywords.com/html-morsels/)
  // Distributed under the Creative Commons
  // "Attribution-NonCommercial-ShareAlike 2.0" License
  // (http://creativecommons.org/licenses/by-nc-sa/2.0/)

        // REMOVED - CC

function trigger_effect(e, div_id, effect, first_img, second_img) {

        Effect.toggle(div_id, effect);
        image = e.getElementsByTagName('img')[0];

        image.src = ( image.src.indexOf(first_img) > -1 ) ? second_img : first_img;
        return true;
}

// control effect on element, only dlide down if not active and vice-versa
function slideToggleDiv( div , action ){

        if (action == null) {
        if ($(div).style.display != 'none') //currently active
                new Effect.SlideUp(div);
        else
                new Effect.SlideDown(div);
        }

        if (action == 'yes'){
                if ($(div).style.display == 'none' )
                        new Effect.SlideDown(div);
        }

        if (action == 'no'){
                if ($(div).style.display != 'none' )
                        new Effect.SlideUp(div);
        }

}

function isIE(){
        if(document.all){
                return true;
        }else{
                return false;
        }
}

function getMouseX(e){
        var x = 0;
        if (!e) var e = window.event;
        if (e.pageX)
        {
                x = e.pageX;
        }
        else if (e.clientX )    {
                x = e.clientX + document.body.scrollLeft+ document.documentElement.scrollLeft;
        }
        return x;
}

function getMouseY(e){
        var y = 0;
        if (!e) var e = window.event;
        if (e.pageY)
        {
                y = e.pageY;
        }
        else if (e.clientY) {
                y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
        }

        return y;
}

/*
This function takes ID of a select element and sets its selected value to the index of the value specified
*/

function Select_Value_Set(SelectId, Value) {
        var SelectObject = $(SelectId);
        for(index = 0; index < SelectObject.length; index++) {
                if(SelectObject[index].value == Value) SelectObject.selectedIndex = index;
        }
}

function toggleSubmit(c, b){
        var button = $(b);
        button.disabled = !c.checked;

        if(c.checked){
                button.removeClassName('disabledButton');
                button.addClassName('bigButton');
        }else{
                button.removeClassName('bigButton');
                button.addClassName('disabledButton');
        }
}

function validateCheck(checkBoxName,msg) {
  if ($(checkBoxName) != null) {
    if ($(checkBoxName).checked == false) {
    // $("error_message").show();
      alert(msg);
      return false;
    } else {
      jQuery('form').submit();
    }
  } else {
    jQuery('form').submit();
  }
}

function uncheckBox(c){
        //alert($(c));
        if ($(c) != null) {
                $(c).checked = false;
        }
}

function calculate_interest(margin, base, guarantee_fee, updateEl1){
        var v = $(margin).value;
                //alert(v);
        var b = $(base);
                //alert(b);
        if(v != "" && !isNaN(v)){
                var i = parseFloat(v) + parseFloat(b) + parseFloat(guarantee_fee);
                $(updateEl1).update(i.toFixed(2));
                //if(updateEl2){
                //    $(updateEl2).update("+ " + v + "% Margin");
                //}
        }else{
                $(updateEl1).update("__.__");
                //if(updateEl2){
                //    $(updateEl2).update("");
                //}
       }
}

// Find position of object on page
function findPos(obj) {
        var curleft = curtop = 0;
        if (obj.offsetParent) {
                curleft = obj.offsetLeft
                curtop = obj.offsetTop
                while (obj = obj.offsetParent) {
                        curleft += obj.offsetLeft
                        curtop += obj.offsetTop
                }
        }
        return [curleft,curtop];
}

// Call this befre excecuting a link_to_remote
// obj = the link usually 'this'
// lyr - the target div tag
function setLyr(obj,lyr)
{
        var coors = findPos(obj);
        if (lyr == 'testP') coors[1] -= 50;
        var x = $(lyr);
        x.style.top = coors[1] + 'px';
        x.style.left = coors[0] + 'px';
}

// Need to disable enter key on some forms and make it act like a tab
// most useful on large forms and those with auto_complete
function enterAsTab()
{
        for( var f, i = ( f = document.forms ).length; i; addEventListener( f[--i], "keypress", function( evt ){
                var el, l, k = evt.key == 13, e = evt.target;
                if( k && !/textarea|select/i.test( e.type ) && !evt.preventDefault() ){
                        for( l = k = ( el = e.form.elements ).length; el[--k] != e; );
                        while( !(e = el[ k = ++k * ( k < l ) ]).type || e.disabled );
                        e.focus();
                }
        } ) );
}

function checkValidLength(el,len){
                if ( $(el).value.length < len )
                                return false;
                else
                                return true;
        }

function showError(errorMsg) {
  var el = $('rightContainerTop').childElements().find(function(element) {
        if (element.id == 'flash-block') return element;
  });
  $(el).update('<div id="flash-error">'+errorMsg+'</div>');
  new Effect.Highlight("flash-error");
}

function trimNumber(s) {
  while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
  return s;
}

function validateDates(form, date) {
  var elements = form.getElements().findAll(function(element) {
    if (element.tagName.toLowerCase() == 'select' &&
        element.name.match('disbursements')) {
      return element;
    }
  });
  var count = elements.length/3;
  var prevYear, prevMonth, prevDay;
  var arr = date.split('/');
  prevYear = parseInt(trimNumber(arr[0]));
  prevMonth = parseInt(trimNumber(arr[1]));
  prevDay = parseInt(trimNumber(arr[2]));
  var errorMsg = '';
  for (var i = 1; i <= count; i++) {
    if (i == 1) {
      errorMsg = "Please specify a date greater or equal to current date!";
    }
    else {
      errorMsg = "Please specify a date greater than previous date!";
    }
    var year = parseInt(elements.find(function(element) {
      if (element.name == 'disbursements['+i+'][disbursement_date][year]') return element;
    }).value);
    if (year < prevYear) {
      showError(errorMsg);
      return false;
    }
    var month = parseInt(elements.find(function(element) {
      if (element.name == 'disbursements['+i+'][disbursement_date][month]') return element;
    }).value);
    if (year == prevYear && month < prevMonth) {
      showError(errorMsg);
      return false;
    }
    var day = parseInt(elements.find(function(element) {
      if (element.name == 'disbursements['+i+'][disbursement_date][day]') return element;
    }).value);
    if (year == prevYear && month == prevMonth && day < prevDay) {
      showError(errorMsg);
      return false;
    }
    prevYear = year;
    prevMonth = month;
    prevDay = day;
  }
}

// to center an element horizontally and vertically
/*Position.Center = function(element) {
        Mask();

        var dimensions = $(element).getDimensions();
        var margin_left = dimensions.width/2;
        var margin_top = dimensions.height/2;

        $(element).setStyle({
            marginLeft: "-" + margin_left + "px",
            marginTop: "-" + margin_top + "px"
        });
        // the element should remain visible within viewport
        // $(element).scrollTo();
}

Mask = function(){
    GetScroll();
    var d = document.viewport.getDimensions();
    var w = d.width;
    var h = d.height;

    $('vp_mask').show();
    $('vp_mask').setStyle({
        width: w,
        height: h
    })
    SetSB('100%', 'hidden');
    SetScroll(0, 0);
}

Unmask = function(){
    SetScroll(0, yPos);
    SetSB('auto', 'auto');
    $('vp_mask').hide();
}

SetSB = function(height, overflow){
    bod = document.getElementsByTagName('body')[0];
    bod.style.height = height;
    bod.style.overflow = overflow;

    htm = document.getElementsByTagName('html')[0];
    htm.style.height = height;
    htm.style.overflow = overflow;
}

var yPos;

GetScroll = function(){
    if (self.pageYOffset) {
            yPos = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop){
            yPos = document.documentElement.scrollTop;
    } else if (document.body) {
            yPos = document.body.scrollTop;
    }
}

SetScroll = function(x, y){
    window.scrollTo(x, y);
}*/

/*-----------------------------------------------------------------------*/
popupbox = function(){
    var yPos = 0;

    return {
        // initializes the popup box
        init: function(element){
            this.getScroll();
            this.setScroll(0, 0);
            this.setViewPort('100%', 'hidden'); // changed from auto, hidden
            this.showMask();
            new Effect.Appear(element);
            this.center(element);

            // add event listner for esc key
            Event.observe(document, 'keypress', function(e){
                if(e.keyCode == Event.KEY_ESC){
                    popupbox.cleanUp(element);
                }
            });
        },

        // hides the popup box
        cleanUp: function(element){
            this.hideMask();
            new Effect.Fade(element, {
                afterFinish: function(){
                    popupbox.setViewPort('100%', 'auto'); // changed from auto,auto - CC
                    popupbox.setScroll(0, yPos);
                }
            });

            // detach event listener
            Event.stopObserving(document, 'keypress');
        },

        // sets the element position center horizontally & vertically to the viewport
        center: function(element){
            var dimensions = $(element).getDimensions();
            var margin_left = dimensions.width * .6; // changed from/2 - CC
            var margin_top = dimensions.height * .6;

            $(element).setStyle({
                marginLeft: "-" + margin_left + "px",
                marginTop: "-" + margin_top + "px"
            });
        },

        // gets the window scrollbar position
        getScroll: function(){
            if (self.pageYOffset) {
                yPos = self.pageYOffset;
            } else if (document.documentElement && document.documentElement.scrollTop){
                yPos = document.documentElement.scrollTop;
            } else if (document.body) {
                yPos = document.body.scrollTop;
            }
        },

        // sets the window scrollbar position
        setScroll: function(x, y){
            //window.scrollTo(x, y); //turn off scroll -CC
        },

        // sets the height and overflow of the viewport
        setViewPort: function(height, overflow){
            var b = document.getElementsByTagName('body')[0];
            b.style.height = height;
            //b.style.overflow = overflow;

            var h = document.getElementsByTagName('html')[0];
            h.style.height = height;
            //h.style.overflow = overflow;
        },

        // adds necessary markup to create the mask behind the popup
        createMask: function(){
            var b = document.getElementsByTagName('body')[0];
            var mask = document.createElement('div');
            mask.id = 'vp_mask';

            b.appendChild(mask);
        },

        // displays the mask
        showMask: function(){
            // create the mask if doesn't exist
          //  if($$('vp_mask').size == 0){
          //      this.createMask();
          //  }

            var doc = document.viewport.getDimensions();
                                                var site =  $('siteContainer').getDimensions();
            var w = doc.width; // 0r 100%
            var h = site.height; // 100% does not work well here

            $('vp_mask').show();
            $('vp_mask').setStyle({
                width: w,
                height: h
            });
        },

        // hides the mask
        hideMask: function(){
            $('vp_mask').hide();
        }
    };
}();


/* Tab for admin reporting */

function tabIn() {
                        tab1 = $('right_azat');
                        tab1.style.cssFloat = "left";
                        tab1.style.marginLeft = "18px";
                        tab2 = $('leftside');
                        tab2.style.width = "0px";
                        tab2.style.overflow = "hidden";
                        tab3 = $('reptab');
                        tab3.style.display = ('none');
                        tab4 = $('reptab2');
                        tab4.style.display = ('block');
}
function tabOut() {
                        tab1 = $('right_azat');
                        tab1.style.cssFloat = "right";
                        tab1.style.marginLeft = "0px";
                        tab2 = $('leftside');
                        tab2.style.width = "175px";
                        tab2.style.overflow = "auto";
                        tab3 = $('reptab');
                        tab3.style.display = ('block');
                        tab4 = $('reptab2');
                        tab4.style.display = ('none');
}

/* Progress Bar Showing and Hiding */
/* TODO: Consolidate in to 1 set -- 3 are not required */

function showProgress1(){
        hiddenDiv1 = $('hidden1');
        hiddenDiv1.style.display = 'block'
}

function hideProgress1(){
        hiddenDiv1 = $('hidden1');
        hiddenDiv1.style.display = 'none'
}

function showProgress2(){
        hiddenDiv2 = $('hidden2');
        hiddenDiv2.style.display = 'block'
}

function hideProgress2(){
        hiddenDiv2 = $('hidden2');
        hiddenDiv2.style.display = 'none'
}

function showProgress3(){
        hiddenDiv3 = $('hidden3');
        hiddenDiv3.style.display = 'block'
}

function hideProgress3(){
        hiddenDiv3 = $('hidden3');
        hiddenDiv3.style.display = 'none'
}

/* Tips */
function makeToolTips(){
    var allTips = $$('div.tooltip_link', 'span.tooltip_link' , 'img.tooltip');  //select all divs and span with a title
    //alert(allTips.length);

    for (var i = 0; i < allTips.length; i++){
        tipInfo = allTips[i].id.split("_"); // function_<click|roll>_infomation_uniqueID

        showMode = (tipInfo[1] == 'c') ? 'click' : 'mouseover';

        //alert(tipInfo);
        switch(tipInfo[0]){
        case 'basic': makeBasicTip(allTips[i], allTips[i].description, showMode); break; // basic tip, shows description text - info is ignored
        case 'div': makeDivTip(allTips[i], tipInfo[2], showMode, '280px'); break;        // shows a hidden div specified in info
        case 'widediv': makeDivTip(allTips[i], tipInfo[2], showMode, '340px'); break;    // just a little wider
        case 'verywidediv': makeDivTip(allTips[i], tipInfo[2], showMode, '420px'); break;    // just a little wider
        case 'ajax': makeAjaxTip(allTips[i], tipInfo[2], showMode); break;               // ajax call -partial to show passed as info argument
        case 'yml': makeYmlTip(allTips[i], tipInfo[2], showMode); break;                 // show tip from YML file
        default: break;
        }

        //new Tip(allTips[i],allTips[i].title);
        //alert(allTips[i].title);
    }
}

function makeBasicTip(node, info, showMode){
        hideMode = (showMode == 'mouseover') ? {element: 'tip', event: 'mouseout'} : {element: 'closeButton',event: 'click'};
        new Tip(node, info, {
                showOn: showMode,
                title: node.title,
                closeButton: 'show',
                hideOn: hideMode,
                width: '280px',
                hook: {target: 'bottomLeft',tip: 'topLeft'},
                stem: 'topLeft',
                offset: {x: 10,y: 0}
        });
}

function makeDivTip(node, info, showMode, width){
        hideMode = (showMode == 'mouseover') ? {element: 'tip', event: 'mouseout'} : {element: 'closeButton',event: 'click'};
        new Tip(node, $(info), {
                //border: 5,
                showOn: showMode,
                title: node.title,
                closeButton: 'show',
                hideOn: hideMode,
                width: width,
                hook: {target: 'bottomLeft',tip: 'topLeft'},
                stem: 'topLeft',
                offset: {x: 10,y: 0}
        });
}

function makeAjaxTip(node, info, showMode){
        hideMode = (showMode == 'mouseover') ? {element: 'tip', event: 'mouseout'} : {element: 'closeButton',event: 'click'};
        new Tip(node, {
                showOn: showMode,
                title: node.title,
                closeButton: 'show',
                ajax: {url: '/tips?partial=' + info,options: {onComplete: function(transport){}}},
                hideOn: hideMode,
                width: '280px',
                hook: {target: 'bottomLeft',tip: 'topLeft'},
                stem: 'topLeft',
                offset: {x: 10,y: 0}
        });
}

function makeYmlTip(node, info, showMode){
        hideMode = (showMode == 'mouseover') ? 'mouseout' :  {element: 'closeButton',event: 'click'};
        new Tip(node, {
                showOn: showMode,
                title: node.title,
                closeButton: 'show',
                ajax: {url: '/tips?tooltip=' + info,options: {onComplete: function(transport){}}},
                hideOn: hideMode,
                width: '280px',
                hook: {target: 'bottomLeft',tip: 'topLeft'},
                stem: 'topLeft',
                offset: {x: 10,y: 0}
        });
}


function displayTool(node){
        var tippyTool = node.parentNode.id;
        new Tip(tippyTool, {
                showOn: 'click',
                title: node.title,
                ajax: {url: '/tips?tooltip=' + tippyTool,options: {onComplete: function(transport){}}},
                hideOn: {element: 'closeButton',event: 'click'},
                width: '300px',
                hook: {target: 'bottomRight',tip: 'topLeft'},
                stem: 'topLeft',
                offset: {x: 0,y: 0}
        });


};


                //function to switch tabs, you have to pass it a jQuery object of a tab and it will do the trick
                //function switch_tabs(tab_obj){

                //}
/* Not sure yet - from Eduard TODO: rewrite for jquery */

if (typeof jQuery != 'undefined') {
  jQuery.ajaxSetup({
    'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript") }
  });
  // remote links
  jQuery('a[data-remote=true]').live('click', function(evt) {
    evt.stopPropagation();
    evt.preventDefault();

    var a = jQuery(this);
    var conf = a.attr('data-confirm');
    if (conf) {
      if (!confirm(conf)) {
        return false;
      };
    };
    var method = a.attr('data-method') || 'post';
    jQuery.ajax({
      url:a.attr('href'),
      type:method,
      dataType:'script'
    });
  });
  // remote forms
  jQuery('form[data-remote=true]').live('submit', function(evt) {
    evt.stopPropagation();
    evt.preventDefault();

    var form = jQuery(this);
    var conf = form.attr('data-confirm');
    if (conf && !confirm(conf)) {
      return false;
    };
    var method = form.attr('data-method') || 'post';
    jQuery.ajax({
      type:method,
      url:form.attr('action'),
      data:form.serialize(),
      dataType:'script'
    });
  });
};

if (Event.addBehavior) {
  Event.addBehavior.reassignAfterAjax=true;
  Event.addBehavior({
      "form":function() {
        var form = $(this);
        var remote = form.readAttribute('data-remote');
        if (remote) {
          form.observe('submit', function(evt) {
              var form = $(evt).element();
              var method = form.readAttribute('data-method') || 'POST';
              var disable_with = form.readAttribute('data-disable-with');
              if (disable_with) {
                form.select('input[type=submit]').each(function(s) {
                    s.disabled=true;
                    s.value=disable_with;
                  });
              };
              new Ajax.Request(form.action,
                {
                  parameters:form.serialize(true),
                  method:method
                }
              );
              evt.stop();
              return false;
            });
        };
      }
    });
};
