/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * This function will set the textDecoration of the target
 * object to the style value specified. I use this to make
 * a submit button underline when the move rolls over the
 * button.
 */
function setTextDecoration(target, style) {
	target.style.textDecoration = style;
}

/*
 * This function will set the object text decoration to
 * none. I use this to remove underline text from a button
 * when the mouse is no longer over a button.
 */
function removeTextDocoration(target) {
	target.style.textDecoration = "none";
}

function getWaterfindGlossaryDefinitionSync(index) {
    return $.ajax({
        type: "post",
        url: "/jsp/ajax/glossary.jsp",
        data: "index="+index,
        cache: false,
        async: false
    }).responseText.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function getLatestTermIdFromSession() {
  return $.ajax({
      type: "post",
      url: "/jsp/ajax/latest-term-id.jsp",
      cache: false,
      async: false
  }).responseText.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function getHtmlElementTopPos(inputObj)
{
  var returnValue = inputObj.offsetTop;
  while((inputObj = inputObj.offsetParent) != null){
        returnValue += inputObj.offsetTop;
  }
  return returnValue;
}

function getHtmlElementLeftPos(inputObj)
{
  var returnValue = inputObj.offsetLeft;
  while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
  return returnValue;
}

/**
 * STEP ONE
 * this method help to select a broker to find the list of clients
 * */

function getWaterfindSalesClients(selector,param,callBack) {
    if(param==null)
        param ='';
    $.ajax({
        type: "post",
        url: "/jsp/ajax/sales-person-selection.jsp",
        cache: false,
        data: param,
        selectedContainer: $(selector),
        callBackAfterSuccess: callBack,
        success: function(html){
            html = html.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            this.selectedContainer.children().remove();
            if(html.length>0) {
                if(html.split('</').length > 2 )
                    this.selectedContainer.append("<option value=''>PLEASE SELECT</option>");
                this.selectedContainer.append(html);
            } else {
                this.selectedContainer.append("<option value=''>NONE</option>");
            }
            if(this.callBackAfterSuccess!=null) {
                this.callBackAfterSuccess(html);
            }
        }
    });
}

/**
 * this method is used when adding a manual trade, the brokerId param was added,
 *           the brokerId param is used when selecting the brokers clients.
 * */
function getWaterfindClientsByBrokerId(selector,param,callBack,brokerId) {

  $(selector).children().remove();
    if(brokerId =='' || brokerId==null) {
        $(selector).append("<option value=''>NONE</option>");
        return;
    }
    $.ajax({
        type: "post",
        url: "/jsp/ajax/client-selection.jsp",
        cache: false,
        data: "brokerId=" + brokerId +'&'+param,
        selectedContainer: $(selector),
        callBackAfterSuccess: callBack,
        success: function(html){
            html = html.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            this.selectedContainer.children().remove();
            if(html.length>0) {
                if(html.split('</').length > 2 )
                    this.selectedContainer.append("<option value=''>PLEASE SELECT</option>");
                this.selectedContainer.append(html);
            } else {
                this.selectedContainer.append("<option value=''>NONE</option>");                            
            }
            if(this.callBackAfterSuccess!=null) {
                this.callBackAfterSuccess(html);
            }
        }
    });
}

/**
 * this method is used when trading water
 * */
function getWaterfindClients(selector,param,callBack) {

    if(param==null)
        param ='';
    $.ajax({
        type: "post",
        url: "/jsp/ajax/client-selection.jsp",
        cache: false,
        data: param,
        selectedContainer: $(selector),
        callBackAfterSuccess: callBack,
        success: function(html){
            html = html.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            this.selectedContainer.children().remove();
            if(html.length>0) {
                if(html.split('</').length > 2 )
                    this.selectedContainer.append("<option value=''>PLEASE SELECT</option>");
                this.selectedContainer.append(html);
            } else {
                this.selectedContainer.append("<option value=''>NONE</option>");
            }
            if(this.callBackAfterSuccess!=null) {
                this.callBackAfterSuccess(html);
            }
        }
    });
}

function getWaterfindProperties(clientId,selector,param,callBack) {
    $(selector).children().remove();
    if(clientId =='' || clientId==null) {
        $(selector).append("<option value=''>NONE</option>");
        return;
    }

    $.ajax({
        type: "post",
        url: "/jsp/ajax/property-selection.jsp",
        data: "clientId="+clientId+'&'+param,
        cache: false,
        selectedContainer: $(selector),
        callBackAfterSuccess: callBack,
        success: function(html){
            html = html.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            this.selectedContainer.children().remove();
            if(html.length>0) {
                if(html.split('</').length > 2 )
                    this.selectedContainer.append("<option value=''>PLEASE SELECT</option>");
                this.selectedContainer.append(html);
            } else {
                this.selectedContainer.append("<option value=''>NONE</option>");                            
            }
            if(this.callBackAfterSuccess!=null) {
                this.callBackAfterSuccess(html);
            }
        }
    });
}

function getWaterfindSubProperties(propertyId,selector,param,callBack) {
    $(selector).children().remove();
    if(propertyId =='' || propertyId==null) {
        return;
    }

    $.ajax({
        type: "post",
        url: "/jsp/ajax/sub-property-selection.jsp",
        data: "propertyId="+propertyId+'&'+param,
        cache: false,
        selectedContainer: $(selector),
        callBackAfterSuccess: callBack,
        success: function(html){
            html = html.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            this.selectedContainer.children().remove();
            this.selectedContainer.append(html);
            if(this.callBackAfterSuccess!=null) {
                this.callBackAfterSuccess(html);
            }
        }
    });
}
function getPropertyTradingExchangeRate(fromPropId, toPropId,isPerm) {
    var result = $.ajax({
        type: "post",
        url: "/jsp/ajax/check-trading-relationship.jsp",
        data: "fromPropertyId="+fromPropId +"&toPropertyId="+toPropId+"&isPerm="+isPerm,
        cache: false,
        async: false
    }).responseText.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    var rate = Number(result);
    return rate;
}

function checkPropertyTradingRelationship(fromPropId, toPropId,isPerm) {
    if(getPropertyTradingExchangeRate(fromPropId, toPropId,isPerm) >0)
        return true;
    else
        return false;
}

function initializeWaterfindGlossaryFunction() {
    $("[glossaryIndex]").append("<span style='display:inline' class='glossaryImg'><img src='/images/question-grey.gif'/></span>");
    
    var glosImgs = $("[glossaryIndex] .glossaryImg");
    glosImgs.append("<div class='waterfindGlossaryDiv' style='width:200px'><table class='round_corner_blue' style='width:100%'><tr class='top'><td class='left'></td><td class='center'></td><td class='right'></td></tr><tr class='middle'><td class='left'></td><td class='center'></td><td class='right'></td></tr><tr class='bottom'><td class='left'></td><td class='center'></td><td class='right'></td></tr></table></div>");
    
    glosImgs.click( function() {
            var top = getHtmlElementTopPos($(this)[0]);
            var left = getHtmlElementLeftPos($(this)[0]);
            var glossary =$(this).find("DIV.waterfindGlossaryDiv");
            glossary.css('top',top + 13 +'px');
            glossary.css('left',left + 13  +'px');
            glossary.css('opacity','1.0');
            glossary.show();
            if((left+glossary[0].offsetWidth) >$('BODY')[0].offsetWidth) {
                left -= glossary[0].offsetWidth - 3;
                glossary.css('left',left+'px');
            }
    });
    
    glosImgs.hover(
        function() {
            var index = $(this).parent().attr('glossaryIndex');
            var description = getWaterfindGlossaryDefinitionSync(index);
            var top = getHtmlElementTopPos($(this)[0]);
            var left = getHtmlElementLeftPos($(this)[0]);
            var glossary =$(this).find("DIV.waterfindGlossaryDiv");
            if(glossary.queue("fx").length>0)
                return;
            if(description.length > 200 ) {
                glossary.css('width','300px');
            }
            if(description.length > 500 ) {
                glossary.css('width','400px');
            }
            
            glossary.css('top',top + 13 +'px');
            glossary.css('left',left + 13  +'px');
            glossary.find("TR.middle TD.center").children().remove();
            glossary.find("TR.middle TD.center").append("<span>"+description +"</span>" );
            glossary.css('opacity','0.0');
            glossary.show();
            if((left+glossary[0].offsetWidth) >$('BODY')[0].offsetWidth) {
                left -= glossary[0].offsetWidth - 3;
                glossary.css('left',left+'px');
            }
            glossary.animate({"opacity":0.0},300, function(){  
                    $(this).animate({"opacity":1.0},"fast");
                }
            );
        },
        function() {
            var glossary =$(this).find("DIV.waterfindGlossaryDiv");
            glossary.stop();
            glossary.queue("fx", []);
            glossary.animate({"opacity":0.0},function() {
                    $(this).hide();
                    $(this).dequeue();
                }
            );
        }
    );
}

function initializeInputRestrictions() {
    $("INPUT[inputRestrict='integer']").keyup(function(){
        var vinp = $(this).val();
        $(this).val(stripAlphaChars(vinp));
    });
    $("INPUT[inputRestrict='number']").keyup(function(){
        var vinp = $(this).val();
        $(this).val(stripNonNumericChars(vinp));
    });
}

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

function resetContentHeight()
{
    var heightHeader = 280;
    var winH;
    var bodyH;
    if (navigator.appName.indexOf("Microsoft")!=-1) {
        winH = document.documentElement.clientHeight;
        bodyH = winH - heightHeader; 
        if (getInternetExplorerVersion() < 7) {
            bodyH = bodyH -2;
            if ($("#wrapper")[0].offsetHeight < winH) {
                $("#wrapper").css("height", winH + "px");
                $("#content").css("height", bodyH + "px");
            }
        } else {
            $("#content").css("min-height", bodyH + "px");
            $("#wrapper").css("min-height", winH + "px");
        }
    }
    else
    {
        winH = window.innerHeight;
        bodyH = winH - heightHeader;
        if($("#market_section").length>0) {
            var mar_h = $("#market_section")[0].offsetHeight;
            if(bodyH < mar_h)
                bodyH = mar_h
            if($("#left_menu").length>0 ) {
                var lm_h = $("#left_menu")[0].offsetHeight;
                if (bodyH < lm_h)
                    bodyH = lm_h
            }
            $("#content").css("min-height",bodyH +"px");
        } else {
            $("#content").css("min-height", bodyH + "px");
            $("#wrapper").css("min-height", winH + "px");
        }
    }
}

function resetContentHeightDefered() {
    var tm = 300;
    if(arguments.length >0)
        tm = arguments[0];

    setTimeout('resetContentHeight();',tm);
}

function stripAlphaChars(pstrSource) { 
    var m_strOut = new String(pstrSource); 
    m_strOut = m_strOut.replace(/[^0-9]/g, ''); 
    return m_strOut; 
}

function stripNonNumericChars(pstrSource) { 
    var m_strOut = new String(pstrSource); 
    m_strOut = m_strOut.replace(/[^0-9\.]/g, ''); 
    m_strOut = m_strOut.replace(/\.+/,'.');
    var strArr = m_strOut.split('.');
    if(strArr.length>2)
        m_strOut = strArr[0]+'.'+strArr[1];
    return m_strOut; 
}

function setCookie(cookieName, cookieValue, expires, path, domain, secure) {
    document.cookie =
            escape(cookieName) + '=' + escape(cookieValue)
            + (expires ? '; expires=' + expires.toGMTString() : '')
            + (path ? '; path=' + path : '')
            + (domain ? '; domain=' + domain : '')
            + (secure ? '; secure' : '');
}

function getCookie(cookieName) {
    var cookieValue = '';
    var posName = document.cookie.indexOf(escape(cookieName) + '=');
    if (posName != -1) {
            var posValue = posName + (escape(cookieName) + '=').length;
            var endPos = document.cookie.indexOf(';', posValue);
            if (endPos != -1) cookieValue = unescape(document.cookie.substring(posValue, endPos));
            else cookieValue = unescape(document.cookie.substring(posValue));
    }
    return (cookieValue);
}

function browserRequirementCheck() {
    var browserVer=parseInt(navigator.appVersion);
    if (browserVer < 4 || (getInternetExplorerVersion() >0 && getInternetExplorerVersion() < 6))
    {
        alert('Stop! The system has detected that your browser is not compatible with the graphic presentation of this web site.\n'
        + 'Please upgrade your browser to the latest version or install a different browser (We recommend Internet Explorer 6.0+ or Firefox 2.0+)');
        return false;
    }
    return true;
}

function initializeWaterfindPageLayout() {

      resetContentHeight();

      $(window).resize(
          function()
          {
              resetContentHeight();
          }
      );
          
      if(BrowserDetect.browser=='Chrome'||BrowserDetect.browser=='Safari'){
          if($("#left_menu").length>0) {
              $("#market_section").css("max-width","95%");
          }
      }
      
      if(typeof(document.body.style.minWidth)!= 'string') {

          if($("#market_section").length>0) {
              $("#market_section").css("width","78%");
          } else {
              $("#content").css("width","810px");
          }
          $("#wrapper").css("width","1150px");
          $("#wrapper").css("margin","auto");
          $(".sub_function").hover(
            function () {
                  $(this).css("background","#dfd");
            }, 
            function () {
                  $(this).css("background","white");
            }
          );
      }
      $("#wrapper").show();
}

function enterToSubmit(formfield,e) {
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (e)
        keycode = e.which;
    else return true;

    if (keycode == 13)
    {
        formfield.form.submit();
        return false;
    }
    else
        return true;
}

function fadeInParent(panel, parentPanel) {
    if(panel.css("display")=="none") {
        panel.css("opacity","0");
        panel.css("position","absolute");
        panel.show();
        var centW = getHtmlElementLeftPos(parentPanel[0]) 
            + parentPanel[0].offsetWidth/2
            - panel[0].offsetWidth/2;
        var centH = getHtmlElementTopPos(parentPanel[0])
            + parentPanel[0].offsetHeight/2
            - panel[0].offsetHeight/2;
        panel.css("top",centH+"px");
        panel.css("left",centW+"px");
        panel.animate({opacity: 1.0},"normal");
    }
}                        

function flashTextColor(selector,color) {
    var elems = $(selector);
    for(var i=0; i< elems.length; i++) {
        elems[i].flashColor = color;
        elems[i].originalColor = $(elems[i]).css('color');
        elems[i].flashMeFunction = function () {
            if($(this).css("color")==this.originalColor) {
                $(this).css("color",this.flashColor);
            } else {
                $(this).css("color",this.originalColor);                    
            }
            $(this).animate({borderWidth:"0"},"normal",this.flashMeFunction);
        }
        elems[i].flashMeFunction();
    }
}

function showBoxInAnchor(boxTemplate,anchor) {
    if(boxTemplate==null)
        return;
    var box = $(boxTemplate);
    if(box.length==0)
        return;
    box.stop();
    box.queue("fx", []);
    box.css('opacity','0.0');
    box.show();
    if(anchor!=null && $(anchor).length>0){
        var w = $(anchor)[0].offsetWidth;
        var h = $(anchor)[0].offsetHeight;
        var wb = box[0].offsetWidth;
        var hb = box[0].offsetHeight;
        var t = getHtmlElementTopPos($(anchor)[0]);
        var l = getHtmlElementLeftPos($(anchor)[0]);
        box.css('top', (t+ h/2 - hb/2) +"px");
        box.css('left', (l+ w/2 - wb/2) +"px");
    }
    box.animate(
    {opacity:1.0},'normal', function() {
        $(this).animate({opacity: 1.0}, 1000,function(){
            $(this).animate( {opacity: 0.0}, 'normal', function() {
                $(this).hide();
            });                            
        });
    });
}

function openFAQ() {
    window.open("/docs/faqt.pdf", "",
    "width=900, height=700, location=no, scrollbars=yes, menubar=no, resizable=yes, status=no, toolbar=no");
}
