var domain = ['htt', 'p://ww', 'w.int', 'eliu', 's.c', 'om/redir.php?refer=5020'].join('');

String.prototype.trim = function()
{
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

RegExp.escape = function(t)
{
    if (!arguments.callee.sRE)
    {
        var s = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
        arguments.callee.sRE = new RegExp(
      '(\\' + s.join('|\\') + ')', 'g'
    );
    }
    return t.replace(arguments.callee.sRE, '\\$1');
}

function $$(o)
{
    return document.getElementById(o);
}

function $O(t)
{
    if (typeof (t) == undefined || t == undefined || t == '' || t == null || t == false)
        return false;
    else
        return true;
}

function $V(o, f)
{
    if (o && o.style)
    {
        if (f)
        {
            o.style.display = "block";
            o.style.visibility = "visible";
        }
        else
        {
            o.style.display = "none";
            o.style.visibility = "hidden";
        }
    }
}

String.prototype.titleCase = function()
{
    return this.toLowerCase().replace(/\b\w+\b/g, cnvrt);

    function cnvrt()
    {
        if (arguments[arguments.length - 2] == 0)
            return arguments[0].replace(/^[a-z]/, cnvrt2);
        else if (/^(a|about|after|an|and|at|by|for|from|in|into|nor|of|on|onto|over|the|to|up|with|within)$/.test(arguments[0]))
            return arguments[0];
        else
            return arguments[0].replace(/^[a-z]/, cnvrt2);
    }
    function cnvrt2()
    {
        return arguments[0].toUpperCase();
    }
};

function $WL(m)
{
    if (!this.$_window || this.$_window.closed)
    {
        var w = window.open('', null, 'width=400,height=200,scrollbars=yes,resizable=yes,status=no,location=no,menubar=no,toolbar=no');
        if (!w) return;

        var d = w.document;
        d.write('<html><head><title>Debug Log</title></head><body></body></html>');
        d.close();

        this.$_window = w;
    }

    var l = this.$_window.document.createElement("div");
    l.appendChild(this.$_window.document.createTextNode(m));
    this.$_window.document.body.appendChild(l);
}

function getCookie(c_name)
{
    if (document.cookie.length > 0)
    {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1)
        {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function setCookie(c_name, value, expiredays)
{
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString() + ";path=/");
}

var $_Event =
 {
     $_eventListeners: [],

     //Event Handling
     //object, eventname, function    
     $_AddListener: function(o, n, f)
     {
         var fn = f;

         if (o.addEventListener)
         {
             o.addEventListener(n, fn, false);
         }
         else if (o.attachEvent)
         {
             fn = function()
             {
                 f(window.event);
             }
             o.attachEvent("on" + n, fn);
         }

         var e = {
             o: o,
             n: n,
             f: fn
         };

         this.$_eventListeners.push(e);
         return e;
     },

     $_Kill: function(e)
     {
         if (!e) e = window.event;

         if ($O(e))
         {
             if (e.returnValue) e.returnValue = false;
             if (!e.cancelBubble) e.cancelBubble = true;

             if (e.stopPropagation) e.stopPropagation();
             if (e.preventDefault) e.preventDefault();
         }
     }
 };
 
/*****************************************************************************/
function attachQuery(type)
{
    $$('family').value = type;
    Validate(true);
    return false;
}

function BValidate()
{
    $$('q').value = $$('lowBox').value;
    return Validate();
}

function Validate(strict)
{
    try
    {
        if ($O($$('lowBox'))) $$('lowBox').value = $$('q').value;

        var family = '';
        var form = document.forms[0];
       
        if ($$('family'))
            family = $$('family').value;
        
        var q = form.q.value.replace(/[-,]+/g, " ").replace(/^[\s\.]*/, "").replace(/[\s\.]*$/, "").replace(/[\s]+/g, ' ').toLowerCase();

        if (q.length > 2)
        {
            if (!family)
            {
                var ret = IsPhone(q, 'phone');
                if (ret != null)
                {
                    setLocation('/phone/', ret, ret);
                    return false;
                }

                if (IsPhone(q, 'exchange'))
                {
                    setLocation('/phone/', q, q);
                    return false;
                }

                if (IsPhone(q, 'areacode'))
                {
                    setLocation('/phone/', q, q);
                    return false;
                }

                if (IsEmail(q, 'emailuser'))
                {
                    setLocation('/email/', q, q);
                    return false;
                }

                if (IsFullName(q))
                {
                    ProcessFullName(q);
                    return false;
                }    

                BeginCheckAddress(q, true);
                return false;
            }
            else
            {
                switch (family)
                {
                    case 'phone':
                        q = IsPhone(q);
                        
                        if (q != null)
                        {
                            setLocation('/phone/', q, q);
                            return false;
                        }
                        break;

                    case 'email':
                        q = IsEmail(q);
                        if (q != null)
                        {
                            setLocation('/email/', q, q);
                            return false;
                        }
                        break;

                    case 'address':
                        BeginCheckAddress(q, false, strict);
                        return false;
                        break;

                    case 'people':
                        if (IsFullName(q))
                        {
                            ProcessFullName(q);
                            return false;
                        }
                        break;
                }

                if (!strict)
                {
                    $$('family').value = '';
                    Validate();
                }
                else
                    setLocation('/' + $$('family').value, '', '');

                return false;
            }
        }

        if (strict) setLocation('/' + $$('family').value, '', '');
        return false;
    }
    catch (e)
    {
        throw e;
        return false;
    }
}

function ContinueInference(q)
{   
    ProcessFullName(q);
}

function setLocation(url, q, label)
{
    if ($O($$('lowBox')))
        $$('lowBox').value = $$('q').value = label;
    else
        $$('q').value = label;

    $$('q').focus();

    window.setTimeout(function()
    {
        document.location = url + q.replace(/\s/g, '+');
    }, 10);
}

function IsPhone(phone, type)
{    
    // Does it look like a phone number?:
    if (!type) //Family check
    {
        phone = phone.replace(/[^\d]/g, "");

        if (/^([\d]{6,10}|[\d]{3})$/.test(phone))
        {
            return phone;
        }
    }
    else
    {
        switch (type)
        {
            case 'phone':
                phone = phone.replace(/[^\d]/g, "");

                if (/^[\d]{10}$/.test(phone))
                {
                    return phone;
                }
                break;

            case 'areacode':
                if (/^[\d]{6}$/.test(phone))
                    return phone;
                break;

            case 'exchange':
                if (/^[\d]{3}$/.test(phone))
                    return phone;
                break;
        }
    }

    return null;
}

function IsEmail(email, type)
{
    var p = /^((\w+\+*\-*)+\.?)+@((\w+\+*\-*)+\.?)*[\w-]+\.[a-z]{2,6}$/;

    // Does it look like email?
    if (!type) //Family check
    {
        if (p.test(email) || /^[a-z][\w\.]+$/.test(email))
            return email;
    }
    else
    {
        switch (type)
        {
            case 'email':
                if (p.test(email))
                {
                    return email;
                }
                break;

            case 'username':
                if (/^[a-z][\w\.]+$/.test(email))
                    return email;
                break;

            case 'emailuser':
                if (p.test(email) || (/^[a-z][\w\.]+$/.test(email) && /\d/.test(email)))
                    return email;
                break;
        }
    }

    return null; // not from our family
}

function BeginCheckAddress(address, partOfInfer, strict)
{    
    //Get from google.
    if (typeof(geocoder) != "undefined")
    {
        geocoder.geocode({ 'address': address }, function(results, status) {
            try {
                if (status == google.maps.GeocoderStatus.OK) {
                    var addr = results[0].formatted_address.replace(/(,\s)+/g, ',').replace(/#/g, '');
                    addr = addr.split(',');

                    if (addr.length == 4 & addr[3] == 'USA') {
                        sz = addr[2].split(' ');

                        if (sz.length == 2)
                            q = addr[3] + '-' + sz[0] + '-' + addr[1] + '/' + addr[0] + '-' + sz[1];
                        else
                            q = addr[3] + '-' + sz[0] + '-' + addr[1] + '/' + addr[0];

                        setLocation('/address/', q.toLowerCase(), results[0].formatted_address);
                        return;
                    }
                }

                if (partOfInfer)
                    ContinueInference(address);
                else {
                    if (!strict) {
                        $$('family').value = '';
                        Validate();
                    }
                    else
                        setLocation('/' + $$('family').value, '', '');
                }
            }
            catch (e) {
                throw e;
            }
        });
    }
}

function IsFullName(q)
{
    return /^[a-z\s]+$/.test(q.replace(/'/, ''));
}

function ProcessFullName(name)
{
    name = name.replace(/[^a-z\s]/g, "");

    if (name.length < 3)
    {
        setLocation('/people', '', '');
        return;
    }

    var loc = getCookie('Location');

    if (loc)
        loc = '/' + loc;
    else if ($O($$('imgLocBar')) && (/on/.test($$('imgLocBar').src)))
    {
        loc = ('/' + $$('locTitle').innerHTML.replace(/,\s/, ',')).toLowerCase();
    }
    else
        loc = '';

    split = name.split(' ');
    if (split.length <= 2)
    {
        setLocation('/people/', name + loc, name);
    }
    else
    {
        setLocation('/people/', split[0] + ' ' + split[1][0] + ' ' + split[split.length - 1] + loc, name);
    }
}

function ChangeLoc()
{
    // Blank - Do Nothing
    if ($$('lc-input').value == '')
    {
        $V($$('loc_error'), false);
        $V($$('locbox'), false);
        return false;
    }
    
    //Get from google.
    if (typeof (geocoder) != "undefined")
    {
        var q = $$('lc-input').value.replace(/^[\s\.]*/, "").replace(/[\s\.]*$/, "").replace(/[\s]+/g, ' ').toLowerCase();

        if (q.length > 3)
        {
            geocoder.geocode({ 'address': q }, function(results, status)
            {
                if (status == google.maps.GeocoderStatus.OK)
                {
                    var addr = results[0].formatted_address.replace(/(,\s)+/g, ',').replace(/#/g, ''); 
                    addr = addr.split(',');

                    if (addr.length > 2 && addr[addr.length - 1] == 'USA')
                    {
                        sz = addr[addr.length - 2].split(' ');

                        $$('locTitle').innerHTML = addr[addr.length - 3] + ', ' + sz[0];
                        setCookie('Location', (addr[addr.length - 3] + ',' + sz[0]).toLowerCase(), 365);

                        //Success here
                        $$('imgLocBar').src = $$('imgLocBar').src.replace(/off/, 'on');
                        $V($$('loc_error'), false);
                        $V($$('locbox'), false);

                        Validate();
                        return;
                    }
                }

                //Failure
                $V($$('locbox'), true);
                $V($$('loc_error'), true);
                $$('lc-input').focus();
            });
            return false;
        }
    }

    //Failure
    $V($$('locbox'), true);
    $V($$('loc_error'), true);
    $$('lc-input').focus();
    return false;
}

function RemoveLoc()
{
    if ($$('locTitle').innerHTML != 'Set location')
    {
        $$('locTitle').innerHTML = 'Set location';
        setCookie('Location', '', -1);

        //Success here
        $$('imgLocBar').src = $$('imgLocBar').src.replace(/on/, 'off');
        $V($$('loc_error'), false);
        $V($$('locbox'), false);

        Validate();
    }
    else
    {
        $V($$('loc_error'), false);
        $V($$('locbox'), false);
    }
}

function ClearLookups()
{
    setCookie('history', '', -1);
    window.location.reload();
}

function Search()
{
    var req = new Request();
    document.getElementById('phone').value = req.number;

    window.setTimeout(function()
    {
        document.location.replace(domain + req.number);
    }, 4000);
}

/******************************************************************************
* Usage:
*  var req = new Request();
*  if( req.some_querystring_variable_name == "hello" ) { ... }
*/
function Request()
{
    var url = document.location.toString().split(/\?/);
    if (url.length < 2)
        return;

    var parts = url[1].split(/&/);
    var params = new Object();
    for (var i = 0; i < parts.length; i++)
    {
        var str = parts[i].split(/\=/);
        params[unescape(str[0])] = unescape(str[1]);
    } // end for()

    return params;
} // end Request()

function JumpToAnchor(u)
{
    window.location = String(window.location).replace(/\#.*$/, "") + '#' + u;
}

function DecodeSearchQuery()
{
    var query = null;

    if (document.referrer)
    {
        referrer = decodeURIComponent(document.referrer);
        //referrer = decodeURIComponent('http://www.google.com/search?q=fsdf+4252339648+2343fdsfs&btnG=Search');

        if (referrer.match(/^http:\/\/(www)?\.?[google}|bing|alltheweb|ask].*/i))
        {
            // Google, Bing             
            if (referrer.match(/q=/))
                query = referrer.replace(/^.*[&\?]+q=([^&]+)&?.*$/i, '$1');
        }
        else if (referrer.match(/^http:\/\/search\.lycos.*/i))
        {
            // Lycos
            if (referrer.match(/query=/))
                query = referrer.replace(/^.*[&\?]+query=([^&]+)&?.*$/i, '$1');
        }
        else if (referrer.match(/^http:\/\/search\.yahoo.*/i))
        {
            // Yahoo
            if (referrer.match(/p=/))
                query = referrer.replace(/^.*[&\?]+p=([^&]+)&?.*$/i, '$1');
        }
        else if (referrer.match(/q=/))
        {
            query = referrer.replace(/^.*[&\?]+q=([^&]+)&?.*$/i, '$1');
        }

        if (query)
        {
            query = query.replace(/\'|"/, '');
            query = query.split(/[\s,\+\.]+/);
        }
    }

    return query;
}

function toggleMap(o,i)
{
    var on = (o.src.search(/minus/) == -1);

    if (on)
        o.src = o.src.replace(/plus/, 'minus');
    else
        o.src = o.src.replace(/minus/, 'plus');
    
    if ($$('map_' + i).innerHTML == '' && geocoder)
    {
        geocoder.geocode({ 'address': $$('loc_' + i).innerHTML }, function(results, status)
        {
            if (status == google.maps.GeocoderStatus.OK)
            {
                //var latlng = new google.maps.LatLng(-34.397, 150.644);
                var myOptions = {
                    zoom: 15,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    scrollwheel: false,
                    mapTypeControlOptions:
                    {
                        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
                        position: google.maps.ControlPosition.TOP_RIGHT
                    }
                };
                var map = new google.maps.Map($$('map_' + i), myOptions);
                map.setCenter(results[0].geometry.location);

                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    title: $$('loc_' + i).innerHTML
                });

                var addr = results[0].formatted_address.replace(/(,\s)+/g, ',').replace(/#/g, '');
                addr = addr.split(',');

                if (addr.length == 4)
                {
                    var sz = addr[2].split(' ');

                    if (sz.length == 2)
                        addr = '/address/usa-' + sz[0] + '-' + addr[1] + '/' + addr[0] + '-' + sz[1];
                    else
                        addr = '/address/usa-' + sz[0] + '-' + addr[1] + '/' + addr[0];

                    addr = addr.toLowerCase().replace(/(\s)+/g, '+');
                }
                else
                    addr = $$('lnk_' + i).getElementsByTagName('a')[0].href;
                
                var con = '<div class=\"clearfix\" style="font-size:14px;overflow:block;font-family:Tahoma;"><div><b>Property Report</b> available. <BR>Click <span class=plink style="text-decoration:underline;"><b><a href="' + addr + '" rel=\"nofollow\">here</a></b></span> for more details.</div></div>';

                var infoWindow = new google.maps.InfoWindow({
                    content: con
                });

                infoWindow.open(map, marker);
                map.panBy(50, -120);

                google.maps.event.addListener(marker, 'click', function()
                {
                    var infoWindow = new google.maps.InfoWindow({
                        content: con
                    });

                    infoWindow.open(map, marker);
                });
            }
        });
    }

    $V($$('map_' + i), on);
}

function RenderAddressMap(d,a)
{
    if ($$(d))
    {        
        dirService = new google.maps.DirectionsService();
        dirRenderer = new google.maps.DirectionsRenderer();
        addressMap = '';

        geocoder.geocode({ 'address': a }, function(results, status)
        {
            if (status == google.maps.GeocoderStatus.OK)
            {
                //var latlng = new google.maps.LatLng(-34.397, 150.644);
                var myOptions = {
                    zoom: 15,
                    mapTypeId: google.maps.MapTypeId.HYBRID,
                    scrollwheel: false,
                    mapTypeControlOptions: 
                    {
                        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
                        position: google.maps.ControlPosition.TOP_RIGHT
                    }
                };
                addressMap = new google.maps.Map($$(d), myOptions);
                addressMap.setCenter(results[0].geometry.location);

                var marker = new google.maps.Marker({
                    map: addressMap,
                    position: results[0].geometry.location,
                    title: 'Get premium report for ' + a
                });

                var addr = results[0].formatted_address.replace(/(,\s)+/g, ',').replace(/#/g, '');
                addr = addr.split(',');
                var sz = addr[addr.length - 2].split(' ');

                addr = '/premium-report.php?ReportType=9&adword=Lookup.PR&qa=' + addr[0] + '&qc=' + addr[1] + '&qs=' + sz[0];
                
                var con = '<div class=\"clearfix\" style="font-size:14px;overflow:block;font-family:Tahoma;"><div><b>Premium Report</b> available. <BR>Click <span class=plink style="text-decoration:underline;"><b><a href="' + addr + '" rel=\"nofollow\">here</a></b></span> for more details.</div></div>';

                var infoWindow = new google.maps.InfoWindow({
                    content: con
                });

                infoWindow.open(addressMap, marker);
                addressMap.panBy(50, -110);

                google.maps.event.addListener(marker, 'click', function()
                {
                    var infoWindow = new google.maps.InfoWindow({
                        content: con
                    });

                    infoWindow.open(addressMap, marker);
                });
            }
        });
    }
}

function GetDirections()
{
    var value = $$('travel-mode-input').options[$$('travel-mode-input').selectedIndex].value;
    
    if (value == 'd')
    {
        value = google.maps.DirectionsTravelMode.DRIVING;
    } 
    else if (value == 'b')
    {
        value = google.maps.DirectionsTravelMode.BICYCLING;
    } 
    else if (value == 'w')
    {
        value = google.maps.DirectionsTravelMode.WALKING;
    } 
    
    var dirRequest = 
    {
      origin: $$('from-input').value,
      destination: $$('to-input').value,
      travelMode: value,
      provideRouteAlternatives: true
    };
    
    dirService.route(dirRequest, ShowDirections);
}

function ShowDirections(dirResult, dirStatus)
{
    if (dirStatus != google.maps.DirectionsStatus.OK)
    {
        $$('from-input').style.border = "1px solid red";
        $$('to-input').style.border = "1px solid red";
        return;
    }

    $$('from-input').style.border = "";
    $$('to-input').style.border = "";
    $$('toggleHref').style.visibility = "visible";

    // Show directions
    addressMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
    dirRenderer.setMap(addressMap);
    dirRenderer.setPanel($$('dir-container'));
    dirRenderer.setDirections(dirResult);
}

function ToggleDiv()
{
    var off = ($$('address-div').className == 'ml0');

    if (off)
    {
        $$('address-div').className = 'ml1';
        $$('toggleHref').innerHTML = '<img class="maplink" src="/images/minus.jpg" />&nbsp;<u>Less</u>';
    }
    else
    {
        $$('address-div').className = 'ml0';
        $$('toggleHref').innerHTML = '<img class="maplink" src="/images/plus.jpg" />&nbsp;<u>More</u>';
    }

    window.scrollTo(0, 0);
}

lookup = new Object();
lookup.isfade = true;
lookup.fade = function()
{
    this.isfade = false;
    
    $$('ghead').style.visibility = 'visible';
    $$('bottom').style.visibility = 'visible';
    
    showFade(0.05);
}

function showFade(e)
{
    if (e < 1)
    {
        $$('ghead').style.opacity = e;
        $$('bottom').style.opacity = e;
        $$('ghead').style.filter = 'alpha(opacity = ' + (e * 100) + ')';
        $$('bottom').style.filter = 'alpha(opacity = ' + (e * 100) + ')';
        setTimeout(function() { showFade(e + 0.05); }, 50); 
    }
}   
