﻿//this codes adds a click function to anchor tags
//so imagebuttons will works as default buttons
if (typeof(HTMLAnchorElement) != "undefined" ){
   HTMLAnchorElement.prototype.click = function(){
       window.location = this.href;
   };
}

//this codes adds an indexOf function to the array
//if it does not exists already
if(!Array.indexOf){
    Array.prototype.indexOf=function(obj){
        for(var i=0;i<this.length;i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}

    /**************************************************************
	** Function used to open a new window.	
	**
	** Created by:      Gene Ernst
	** Last modified:	1/17/2007										
	***************************************************************/	
function PopUpWindow(strURL, strWidth, strHeight, strLeft, strTop, strStatus, strLoc, strToolbar, strMenu, strScroll, strResize) 
{	
	var DocWindow
	
	if (DocWindow && !DocWindow.closed)
		{
		    DocWindow.close();
		}
	
	DocWindow = window.open(strURL,"DocWindow","width="+strWidth+",height="+strHeight+",left="+strLeft+",top="+strTop+",status="+strStatus+",location="+strLoc+",toolbar="+strToolbar+",menubar="+strMenu+",scrollbars="+strScroll+",resizable="+strResize+"");
	DocWindow.focus; 
}	 


function openWin(url,windowName,options){
	var WindowHandle=window.open(url,windowName,options);
	WindowHandle.focus();
}
function openmyweichert() {
    MWopenPopupStart();
}
function ImgChange(imgName,imgSrc){
    var target = eval(imgSrc);
    document.images[imgName].src = target.src;  

    if( ImgResize(target, 240, 320) )
    {
        document.images[imgName].style.height = target.height;  
        document.images[imgName].style.width = target.width;  
    }
}
function SetSize(imgName, maxHeight, maxWidth)
{
    var img = document.getElementById(imgName);
    var copy = new Image();
    copy.src = img.src;
    if(ImgResize(copy, maxHeight, maxWidth))
    {
        img.style.height = copy.height + 'px';  
        img.style.width = copy.width + 'px';  
    }
}
function SetSizeByName(imgName, maxHeight, maxWidth)
{
    var img = document.images[imgName];
    if (img == undefined || img == null) return;
    var copy = new Image();
    copy.src = img.src;
    if(ImgResize(copy, maxHeight, maxWidth))
    {
        img.style.height = copy.height + 'px';  
        img.style.width = copy.width + 'px';  
    }
}
function ImgResize(img, maxHeight, maxWidth) 
{
    if (img == undefined || img == null) return false;
    if (maxHeight == 0 || maxWidth == 0 ) return false;
    if (img.height == 0 || img.width == 0 ) return false;

    var targetRatio;
    targetRatio = maxWidth / maxHeight;
    var imgRatio;
    imgRatio = img.width / img.height;
    
    if( targetRatio == imgRatio )
    {
         img.height = maxHeight;
         img.width = maxWidth;
    }
    else if (targetRatio > imgRatio) 
    {
        img.width = maxHeight * imgRatio;
        img.height = maxHeight;
    }
    else 
    {
        img.height = maxWidth / imgRatio;
        img.width = maxWidth;
    }
    return true;
}
function NextImage(imgName, fullImages){
    var index;
    for( index = 0; index < fullImages.length-1; index++ )
    {
        if( fullImages[index].src == document.images[imgName].src )
        {
            ImgChange(imgName,fullImages[index + 1].id);
            break;
        }
    }
}
function PreviousImage(imgName, fullImages){
    var index;
    for( index = fullImages.length-1; index > 0; index-- )
    {
        if( fullImages[index].src == document.images[imgName].src )
        {
            ImgChange(imgName,fullImages[index - 1].id);
            break;
        }
    }
}


//TODO: Homestore
function SaveSearch(saveURL){
    window.top.location.href="../../myweichert/savedsearches.aspx?Action=Save&search=hs&hq=" + escape(saveURL)
    //alert("../../myweichert/savedsearches.aspx?Action=Save&hq=" + escape(saveURL))
}
//TODO: Homestore
function SaveListing(MlsName, MlsNumber, PerPopulatedSaveName){
    window.top.location.href="../../myweichert/savedlistings.aspx?ID=0&Action=Save&hs=1&MlsNumber=" + escape(MlsNumber) + "&MlsName=" + escape(MlsName) + "&Name=" + escape(PerPopulatedSaveName)
    //alert("../../myweichert/savedlistings.aspx?Action=Save&propertyID=" + escape(propertyID) + "&PerPopulatedSaveName=" + escape(PerPopulatedSaveName))
}

function externalLinks(elem) 
{
    if (!elem.getElementsByTagName){ return; }
    var anchors = elem.getElementsByTagName("a");
    for (var i=0; i<anchors.length; i++) 
    {
        var anchor = anchors[i];
        if (anchor.getAttribute("href"))
        {
         anchor.target = "_blank";
        }
    }
}

function CreateXMLDocumentFromString( xmlText )
{
    var doc = null;
    // code for IE
    if (window.ActiveXObject)
    {
        var doc=new ActiveXObject("Microsoft.XMLDOM");
        doc.async="false";
        doc.loadXML(xmlText);
    }
    // code for Mozilla, Firefox, Opera, etc.
    else
    {
      var parser=new DOMParser();
      var doc=parser.parseFromString(xmlText,"text/xml");
    }
    return doc;
}
function CreateXMLDocument()
{
    var xmlDoc = null;
    // code for IE
    if (window.ActiveXObject)
    {
	    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	    xmlDoc.async=false;
    }
    // code for Mozilla, Firefox, Opera, etc.
    else if (document.implementation && document.implementation.createDocument)
    {
	    xmlDoc=document.implementation.createDocument("","",null);
    }
    else
    {
        //error
	    alert('Your browser cannot handle this script');
    }
    return xmlDoc;
}

function ProcessCallBackResult(result, context)
{
    var results = result.split('&');
    for( var i = 0; i < results.length; i++ )
    {
        var item = results[i];
        var key = item.split('=')[0];
        var value = unescape(item.split('=')[1]);
        value = value.replace(/\+/gi, ' ');

        if(key.toLowerCase() == "redirect")
        {
            location.href = value;
            return;
        }
        else
        {
            document.getElementById(key).innerHTML = value;        
        }
    }
}
function ClientCallbackError(result, context)
{
    alert("An error has occured, please try again.");
}

    /**************************************************************
	** Function to test for numeric value.	
	** Returns false if value passed is not a numeric value
	** 
	** Created by:      Gene Ernst
	** Last modified:	1/17/2007										
	***************************************************************/
function IsNumeric(strString)   
{
    var strValidChars = "0123456789.-";
    var strChar;
    var blnResult = true;

    if (strString.length == 0) return false;

    //  test strString consists of valid characters listed above
    for (i = 0; i < strString.length && blnResult == true; i++)
        {
            strChar = strString.charAt(i);
            if (strValidChars.indexOf(strChar) == -1)
            {
                blnResult = false;
            }
        }
   return blnResult;
}

function showPopup(id)
{
    document.getElementById(id).style.display = "";
    return false;
}
function hidePopup(id)
{
    document.getElementById(id).style.display = "none";
    return false;
}

/*
   name - name of the cookie
   value - value of the cookie
   [expires] - expiration date of the cookie
     (defaults to end of current session)
   [path] - path for which the cookie is valid
     (defaults to path of calling document)
   [domain] - domain for which the cookie is valid
     (defaults to domain of calling document)
   [secure] - Boolean value indicating if the cookie transmission requires
     a secure transmission
   * an argument defaults when it is assigned null as a placeholder
   * a null placeholder is not required for trailing omitted arguments
*/

function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}


/*
  name - name of the desired cookie
  return string containing value of specified cookie or null
  if cookie does not exist
*/

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

function addCommas(nStr)
{
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function handleEnter(field, event, buttonid) {
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (keyCode == 13) {
        document.getElementById(buttonid).onclick();
	    return false;
    } 
    else
    return true;
}     

function addEvent(context, eventName, handler){
    if(context) {
        //strip off 'on' prefix for use with addEventListener
        if(eventName.substring(0, 2) == "on") {
            eventName = eventName.substring(2,eventName.length);
        }
        if (context.addEventListener){
            context.addEventListener(eventName, handler, false);
        } 
        else if (context.attachEvent){
            context.attachEvent("on"+eventName, handler);
        }
    }
}

function makeExternalLinks() { 
    if (!document.getElementsByTagName) return; 

    var anchors = document.getElementsByTagName("a"); 
    for (var i=0; i<anchors.length; i++) { 
        var anchor = anchors[i]; 
        var relvalue = anchor.getAttribute("rel");

        if (anchor.getAttribute("href")) {
            var external = /external/;
            var relvalue = anchor.getAttribute("rel");
            if (external.test(relvalue)) { anchor.target = "_blank"; }
        }
    } 
} 

function getQueryValue( url, name )
{
  var name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url );
  if( results == null )
    return "";
  else
    return results[1];
}

function switchImage(imgName, imgSrc)

   {
   document.getElementById(imgName).src = imgSrc;
   }
   
function displayFlashVideo(elemId,player, theme, video, height, width, caption, bgColor){
        if(bgColor==null){bgColor="#ffffff";}
		var so = new SWFObject(player, 'player', width, height, '7', bgColor);
		so.addParam("allowScriptAccess","always");
		so.addParam("allowFullScreen","true");
		so.addParam("wmode", "window");
		so.addParam("scale", "noscale");
		so.addVariable("file", video);
		so.addVariable("width", width);
		so.addVariable("height", height);
		so.addVariable("theme", theme);
		// the movie loop parameter - can be set to 0 (the video will stop after the playback is over) or 1 (playback is looped)
		so.addVariable("repeat", "0");
		// the movie automatic startup parameter - can be set to 0 (the playback will not start automatically once the page with the video is loaded) or 1 (autostart)
		so.addVariable("autostart", "0");
		// the name and path of the image that will be displayed when the page is loaded, provided that the autostart value is set to 0 (i.e. no autostart is enabled)
		so.addVariable("image", "");
		// the volume that will be used to playback your movie
		so.addVariable("volume", "50");
		so.addVariable("scaleonresize", "none");
		// the top and the bottom captions displayed when you roll your mouse cursor over the player window
		if(caption){
		so.addVariable("top_caption", caption);
		} else {
		so.addVariable("top_caption", " ");
		}
		so.addVariable("top_caption", " ");
		so.addVariable("bottom_caption", " ");
		so.addVariable("showlogo", "0");
		so.addVariable("v", getQueryParamValue("v"));
		so.write(elemId);
}

String.format = String.prototype.format = function() {
    var i=0;
    var string = (typeof(this) == "function" && !(i++)) ? arguments[0] : this;

    for (; i < arguments.length; i++)
    string = string.replace(/\{\d+?\}/, arguments[i]);

    return string;
}

function setDefaultButton(textbox, button){
    textbox.onkeydown = function(e){
        e = e || window.event;
        var code = e.keyCode || e.which;
        if(code == 13){ button.click();}
    };
}

function htmlEncode(input){
  var t = document.createTextNode(input),
      e = document.createElement('div');
  e.appendChild(t);
  return e.innerHTML;
}

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes[0].nodeValue;
}

function setupInputLabel(label){
    var input = document.getElementById(label.htmlFor);
    (input.value!='') ? label.style.visibility = 'hidden' : label.style.visibility = 'visible';
    addEvent(input,'blur',function(){if(input.value==''){label.style.visibility = 'visible';}});
    addEvent(input,'focus',function(){label.style.visibility = 'hidden';});
    addEvent(input,'keydown',function(){label.style.visibility = 'hidden';});
}

function setupDropDown(elemId){
    var elem = document.getElementById(elemId);
    if(elem.value==''){
        elem.style.color="#999999";
    }
    addEvent(elem,'change',function(){
        if(elem.value==''){
            elem.style.color="#999999";
        }else{
            elem.style.color="";
        }
    });
}

//QueryString object
//uses the pages qs if none is passed in
function Querystring(qs){
	this.values = {};	
	if(qs == null){qs = location.search.substring(1, location.search.length)};
	if(qs.length == 0){return};

    //replace '+' with ' ' and split all name/value pairs
	qs = qs.replace(/\+/g, ' ');
	var pairs = qs.split('&');
	
    // parse each name/value pair
	for(var i=0;i<pairs.length;i++){
		var pair = pairs[i].split('=');
		var name = decodeURIComponent(pair[0]);
		var value = (pair.length==2) ? decodeURIComponent(pair[1]) : null;
		if(!this.contains(name)	){
    		this.values[name] = value;
    	} else {
    	    this.values[name] += ',' + value;
    	}
	}
}
Querystring.prototype.get = function(key, default_){
	var value = this.values[key];
	return (value != null) ? value : default_;
};
Querystring.prototype.contains = function(key){
	var value = this.values[key];
	return (value != null);
};

//HTTP object
/*
 * Make Request
 */
function WDCHttp(url){
    this.http = null;
    this.url = url;
    this.init();
}
WDCHttp.prototype.init = function(){    
    if (typeof XMLHttpRequest != "undefined") {
        this.http = new XMLHttpRequest();
    } else if (typeof ActiveXObject != "undefined") {
        this.http = new ActiveXObject("MSXML2.XmlHttp");
    } else {
        //alert("No XMLHttpRequest object available. This functionality will not work.");
    }
}
WDCHttp.prototype.post = function (context, params, responseCallback) {
    var oHttp = this.http;        
    //if there is already a live request, cancel it
    if (oHttp.readyState != 0) {
        try{
            oHttp.onreadystatechange = function() {};
            oHttp.abort();
        }
        catch(ex) {
            //alert("ex");
        }
    }
    oHttp.open("post", this.url , true);
    oHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    oHttp.setRequestHeader('Content-length', params.length);
    oHttp.setRequestHeader('Connection', 'close');
    oHttp.onreadystatechange = function () {
        if (oHttp.readyState == 4) {
           if(oHttp.responseText){
                var json = oHttp.responseText; 
                var result = eval('(' + json + ')'); 
                //alert(json); 
                if(responseCallback){
                    responseCallback(context,result);
                }
            }
        }    
    };
    oHttp.send(params);
};
WDCHttp.prototype.get = function (context, params, responseCallback) {
    var oHttp = this.http;
    //if there is already a live request, cancel it
    if (oHttp.readyState != 0) {
        this.abort();
    }                 
    var url = this.url + "?" + params;   
    oHttp.open("get", url , true);
    oHttp.onreadystatechange = function () {
        if (oHttp.readyState == 4) {
           if(oHttp.responseText){
                var json = oHttp.responseText; 
                var result = eval('(' + json + ')'); 
                //alert(json); 
                if(responseCallback){
                    responseCallback(context,result);
                }
            }
        }    
    };
    oHttp.send(null);
};
WDCHttp.prototype.abort = function() {
    try
    {
        oHttp.onreadystatechange = function() {};
        oHttp.abort();
    }
    catch(ex) {
        //alert("ex");
    }
};

function ScrollDiv(elemId, anchors){
    this.interval = 10;
    this.defaultSlideDur = 500;
    this.startTime = null;
    this.scrollElem = document.getElementById(elemId);
    this.x = 0;
    this.y = 0;
    this.moveTo(0,0);
    this.container = this.scrollElem.parentNode;
    
    this.maxX = this.scrollElem.offsetWidth - this.container.offsetWidth;
    if(this.maxX<0){ this.maxX=0; }
    this.maxY = this.scrollElem.offsetHeight - this.container.offsetHeight;
    if(this.maxY<0){ this.maxY=0; }

    var context = this;
    this.left = null;
    if(anchors!=null){
        if(anchors.leftId!=null){
            this.left = document.getElementById(anchors.leftId);
            this.left.onclick = function(){context.initGlide(context.container.offsetWidth,0);};
        }
        this.top = null;
        if(anchors.topId!=null){
            this.top = document.getElementById(anchors.topId);
            this.top.onclick = function(){context.initGlide(0,context.container.offsetHeight);};
        }    
        this.right = null;
        if(anchors.rightId!=null){
            this.right = document.getElementById(anchors.rightId);
            this.right.onclick = function(){context.initGlide(-context.container.offsetWidth,0);};
        }
        this.down = null;
        if(anchors.downId!=null){
            this.down = document.getElementById(anchors.downId);
            this.down.onclick = function(){context.initGlide(0,-context.container.offsetHeight);};
       }
    }
};
ScrollDiv.prototype.stopScroll = function() { 
    window.clearTimeout(this.timerId); 
    this.timerId = null;
};
 
ScrollDiv.prototype.initGlide = function(dx, dy,dur) { 
    if ( this.sliding ) return;
    this.startX = this.x; 
    this.startY = this.y;
    this.destX = this.destY = this.distX = this.distY = 0;
    if (dy < 0) {
        this.distY = (this.startY + dy >= -this.maxY)? dy: -(this.startY  + this.maxY);
    } else if (dy > 0) {
        this.distY = (this.startY + dy <= 0)? dy: -this.startY;
    }
    if (dx < 0) {
        this.distX = (this.startX + dx >= -this.maxX)? dx: -(this.startX + this.maxX);
    } else if (dx > 0) {
        this.distX = (this.startX + dx <= 0)? dx: -this.startX;
    }
    
    this.destX = this.startX + this.distX; this.destY = this.startY + this.distY;
    this.slideDur = (typeof dur == 'number')? dur: this.defaultSlideDur;
    this.per = Math.PI/(2 * this.slideDur); this.sliding = true;
    this.startTime = new Date().getTime();
    var context = this;
    this.timerId = window.setInterval(function(){context.glide(dx,dy);},10);
};
ScrollDiv.prototype.glide = function(fx, fy) { 
    var elapsed = new Date().getTime() - this.startTime;
    if (elapsed < this.slideDur) {
        var x = this.startX + Math.round( this.distX * Math.sin(this.per*elapsed) );
        var y = this.startY + Math.round( this.distY * Math.sin(this.per*elapsed) );
        this.moveTo(x, y); 
    } else {	// if time's up
        this.stopScroll();
        this.sliding = false;
        this.moveTo(this.destX, this.destY);
        // end of axis reached ? 
        if ( this.distX && (this.destX == 0 || this.destX == -this.maxX) 
          || this.distY && (this.destY == 0 || this.destY == -this.maxY) ) { 
        } 
    }
};
ScrollDiv.prototype.moveTo = function(x, y) { 
    this.x = x;
    this.scrollElem.style.marginLeft = x + 'px';
    this.y = y;
    this.scrollElem.style.marginLTop = y + 'px';
};

function mouseX(evt) {
    if (evt.pageX) return evt.pageX;
    else if (evt.clientX)
       return evt.clientX + (document.documentElement.scrollLeft ?
       document.documentElement.scrollLeft :
       document.body.scrollLeft);
    else return null;
}
function mouseY(evt) {
    if (evt.pageY) return evt.pageY;
    else if (evt.clientY)
       return evt.clientY + (document.documentElement.scrollTop ?
       document.documentElement.scrollTop :
       document.body.scrollTop);
    else return null;
}

function findPos(obj){
    var left = 0;
    var top = 0;
    if (obj.offsetParent) {
        do {
	        left += obj.offsetLeft;
	        top += obj.offsetTop;
        } while (obj = obj.offsetParent);
	    return {"left":left,"top":top};
    }
}