/* PROPERTIES FILE, THIS WILL LIVE AT TOP OF COMMON */

var _yo_props = {};

_yo_props['server'] = 'http://cloud.yolink.com';



function getYoProp(name)
{
    return _yo_props[name];
}/** Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php

    Copyright (c) 2010 Chris Iona <chris.iona@gmail.com>

    Project:		http://chrisiona.com/fixedposition
  			https://code.google.com/p/fixedposition
    Version:		1.0.0
*/
try{
//for backward compatibility to check if $tigr namespace is valid or not
var isTigrValid  = $tigr;
}catch(e){
//if not valid namaspace assign $tigr back to $
$tigr= $;
}

(function(a){a.fn.fixedPosition=function(c){var d={fixedTo:"bottom",debug:false,effect:false,effectSpeed:1000};var e=a("body");var c=a.extend(d,c);var b=function(){e.append("<style>span#supportsPositionFixed{position:fixed;width:1px;height:1px;top:25px;}</style>");e.append('<span id="supportsPositionFixed"></span>');var f=a("#supportsPositionFixed").offset();a("#supportsPositionFixed").remove();return Boolean(f.top===25)};return this.each(function(){var j=a(this);var g=b();if(d.debug){var m;try{m=document.doctype.publicId}catch(l){try{m=document.getElementsByTagName("!")[0].nodeValue.replace(/^[^\"]*\"([^\"]+)\".*/,"$1")}catch(l){}}var f="<ul><h2>Debug Data</h2>";f+="<li>DOC TYPE: "+m+"</li>";f+="<li>Supports <u>position: fixed</u>: <strong>"+g+"</strong></li>";for(var h in a.browser){f+="<li>"+h+": <strong>"+a.browser[h]+"</strong></li>"}for(var h in d){f+="<li>"+h+": <strong>"+d[h]+"</strong> <em>("+(typeof d[h])+")</em></li>"}f+="</ul>";e.prepend('<div class="debug">'+f+"</div>")}if(!g){j.attr("id",function(i){return(a(this).attr("id").length?a(this).attr("id"):"positionFixedID"+i)});if((e.css("background-image"))=="none"){e.css("background","url(/images/positionFixed.jpg) fixed")}else{e.css("background-attachment","fixed")}var k="";if(d.fixedTo=="top"){k="$(document).scrollTop()"}else{k='$(document).scrollTop() - $("#'+j.attr("id")+'").outerHeight() + (document.documentElement.clientHeight || document.body.clientHeight)'}e.append("<style>.iefixedbar { background: #99CC99; background-image: url(/images/positionFixed.jpg);background-position: fixed; position: absolute; top: expression(eval("+k+"));width: expression(eval(document.documentElement.clientWidth || document.body.clientWidth));}</style>");j.addClass("iefixedbar");if(d.effect){switch(d.effect){case"fadeIn":j.hide().fadeIn(d.effectSpeed);break;case"slideDown":j.hide().slideDown(d.effectSpeed);break}}}})}})($tigr);
if (!tigr) var tigr = {};
if (!tigr.util) tigr.util = {};
if (!tigr.api) tigr.api = {};
if (!inheriting) var inheriting = {};
$tigr.fn.exists = function()
{
    return ($tigr(this).length > 0);
}
if(navigator.userAgent.indexOf('iPad') != -1){$tigr.browser.iPad=true;}
if(navigator.userAgent.indexOf('iPhone') != -1){$tigr.browser.iPad=true;}
if(navigator.userAgent.indexOf('Android') != -1){$tigr.browser.iPad=true;$tigr.browser.android=true;}
// ------------------------------------------------------------------------- //

tigr.api.APIKey = 
{
    key    : undefined,

    getKey : function()
    {
        return this.key;
    },

    setKey : function(k)
    {
        this.key = k;
    }
}

// ------------------------------------------------------------------------- //

tigr.util.isUndefined = function(v)
{
    return ( v == null && v !== null );
}

tigr.util.LETTERS = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
        'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
        'U', 'V', 'W', 'X', 'Y', 'Z' ];

tigr.util.getLetter = function(idx)
{
    var res = '';
    var len = tigr.util.LETTERS.length;

    if (idx >= 0)
    {
        var repeat = Math.floor(( idx / len )) + 1;
        var letter = tigr.util.LETTERS[ ( idx % len ) ];

        for (var i = 0; i < repeat; i++)
        {
            res += letter;
        }
    }

    return res;
}

// ------------------------------------------------------------------------- //
tigr.util.exec = function( args )
{
    var result = null;
    if( args )
    {
        var src = args.src;
        if( src )
        {
            try
            {
                switch( typeof(src) )
                {
                    case 'string':
                        result = args.asstring ? src : $tigr(src, args.root);
                        break;

                    case 'function':
                        result = src(args.root);
                        break;
                }
            }
            catch(e)
            {
                if( args.error )
                {
                    args.error( e );
                }
            }
        }
        else
        {
            result = args.root;
        }

        if( result &&
            args.asstring )
        {
            if( typeof(result) != 'string' )
            {
                var atomize = function(item)
                {
                    var name = $tigr(item).nodeName;
                    if( name )
                    {
                        name = name.toLowerCase();
                        if( name == 'input' ||
                            name == 'select' )
                        {
                            return $tigr(item).val();
                        }
                        else
                        {
                            return $tigr(item).text();
                        }
                    }
                    else
                    {
                        return $tigr(item).toString();
                    }
                }

                var size = $tigr(result).size();
                if( size == 1 )
                {
                    result = atomize( result );
                }
                else
                if( size > 1 )
                {
                    var sb = new tigr.util.StringBuffer();
                    $tigr(result).each(
                        function(index,value)
                        {
                            sb.append( atomize( value ) );
                        } );

                    result = sb.toString();
                }
            }
        }
    }

    return result;
}

// ------------------------------------------------------------------------- //

String.prototype.ltrim = function()
{
    return this.replace(/^\s\s*/, '');
}

String.prototype.rtrim = function()
{
    return this.replace(/\s\s*$tigr/, '');
}

String.prototype.trim = function()
{
    return this.ltrim().rtrim();
}
/**
 * finds if startswith a given str
 */
String.prototype.startsWith = function(str)
{
    var starts = true;
    try
    {
        for (var i = 0; i < str.length; i++)
        {
            if (this.charAt(i) != str.charAt(i))
            {
                starts = false;
                break;
            }
        }

    }
    catch (e)
    {
        starts = false;
    }
    return starts;

}
/**
 *added to compare 2 arrays for equality
 */
Array.prototype.equals = function (array)
{
    var matches = false;
    if (this.length == array.length)
    {
        for (var i = 0; i < array.length; i++)
        {
            if (this[i] == array[i])
            {
                matches = true;
            }
            else
            {
                matches = false;
                break;
            }
        }
    }

    return matches;
}
/**
 * name and value of the cookie and the number of days it is to remain active. I
 *days--variable expires to this date in the UTC/GMT format required by cookies.
 *if 0 is passed to the function, expires is not set and the cookie expires when the user closes his browser..
 */
tigr.util.createCookie = function (name, value, days)
{
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
},
        /**
         *pass the name of the cookie.
         */
                tigr.util.readCookie = function (name)
        {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++)
            {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }
        /**
         *delete a cookie by name
         */
tigr.util.deleteCookie = function (name)
{
    tigr.util.createCookie(name, "", -1);
}

/**
 * find left of element
 */
tigr.util.elemX = function(elem)
{
    var current = 0;
    if (elem.offsetParent)
    {
        while (true)
        {
            current += elem.offsetLeft;
            if (!elem.offsetParent)
            {
                break;
            }

            elem = elem.offsetParent;
        }
    }
    else
        if (elem.x)
        {
            current = elem.x;
        }

    return current;
}
/**
 * encodes the give string using encodeURIComponent() and escapes the single quote
 */
tigr.util.encodeNescapeSingleQuote = function (str)
{
    return encodeURIComponent(str).replace(/'/g, "\\'");
}

/**
 * Function used to determine: 
 * A) If the browser that is being used is IE
 * B) If it is IE then what compatibility mode it is in.
 * The reason is if you do not have the correct doctype declaration 
 * simply just using the most asinine browser on earth (IE), you may 
 * not have support for features like fixed position, or dragging
 * the box on preview mode, etc.  Therefore we have to use special code
 * to handle the lowest common denominator.  
 * 
 * @return: boolean :true if it supports modern css. Generally means not quirks mode. or any other modern browser.
 *                   false if it is IE and can't handle modern css.                     
 */
tigr.util.IESupportsModernCSS = function(document)
{
    var IEengine = null;
    if (window.navigator.appName == "Microsoft Internet Explorer")
    {
        // This is an IE browser. What mode is the engine in?
        if (document.documentMode)
        {
            // IE8
            engine = document.documentMode;
        }
        else
        {
            // IE 5-7 Yes people in IE were hitting the crack pipe.
            // The compatMode property introduced in Internet Explorer 6 is deprecated in
            // favor of the documentMode property introduced in Internet Explorer 8.
            // Applications that currently rely on compatMode  continue to work in
            // Internet Explorer 8; however, they should be updated to use documentMode.

            // Assume quirks mode unless proven otherwise.
            engine = 5;
            if (document.compatMode)
            {
                if (document.compatMode == "CSS1Compat")
                {
                    engine = 7;
                    // standards mode
                }
            }
        }

        if (engine >= 7)
        {
            return true;
        }
        else
        {
            false;
        }
    }
    else
    {
        return true;
    }

}
/**
*checks if the url belongs to the same document domain
*/
tigr.util.isSameDomain = function(url)
{
  var hostname = url.match(/:\/\/(.[^/]+)/)[1];
  return (document.domain == hostname);
}
/**
 * Used to retrieve the baseline url. That is, the url without the clutter of
 * the query string
 * 
 * @param: document The document object in which to determine the current pages url
 * @return: String: The url up to the query string
 *                 
 */
tigr.util.getBaseLineURL = function(document)
{
    var sb = new tigr.util.StringBuffer();
    sb.append(document.location.protocol)
            .append("//")
            .append(document.location.host)
            .append(document.location.pathname);

    return sb.toString();
}
/**
* finds window height and width depending different browser implementations
*/
tigr.util.getWindowWidthHeight = function()
{
        var width = 0;
        var height = 0;
        if (typeof( window.innerWidth ) == 'number')
            {
                //Non-IE
                width = window.innerWidth;
                height = window.innerHeight;
            }
            else if (document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ))
            {
                //IE 6+ in 'standards compliant mode'
                width = document.documentElement.clientWidth;
                height = document.documentElement.clientHeight;
            }
            else if (document.body && ( document.body.clientWidth || document.body.clientHeight ))
            {
                //IE 4 compatible
                width= document.body.clientWidth;
                height = document.body.clientHeight;
            }
       return {width:width,height:height}
}
/**
 * find top of element
 */
tigr.util.elemY = function(elem)
{
    var current = 0;
    if (elem.offsetParent)
    {
        while (true)
        {
            current += elem.offsetTop;
            if (!elem.offsetParent)
            {
                break;
            }

            elem = elem.offsetParent;
        }
    }
    else
        if (elem.y)
        {
            current = elem.y;
        }

    return current;
}
// ------------------------------------------------------------------------- //

/*
 * CLASS      : Dictionary
 * DESCRIPTION: A dictionary implementation in JS.
 */
tigr.util.Dictionary = function()
{
    this.size = 0;

    // Private object to hold properties.
    // ----------------------------------
    var internal = {};

    // Privileged function to get to the internal object.
    // --------------------------------------------------
    this.getInternal = function()
    {
        return internal;
    }
}

/**
 * Removes all mapping from this map.
 */
tigr.util.Dictionary.prototype.clear = function()
{
    var i = this.getInternal();

    for (a in i)
    {
        delete i[ a ];
    }
}

/**
 * Returns true if the given key exists in this map.
 *
 * @param   key     The key to check.
 * @return          true if the key exists.
 */
tigr.util.Dictionary.prototype.containsKey = function(key)
{
    var r = false;
    var i = this.getInternal();

    for (a in i)
    {
        if (a == key)
        {
            r = true;
            break;
        }
    }

    return r;
}

/**
 * Returns true if the given value exists in this map.
 *
 * @param   val     The value to check.
 * @return          true if the value exists.
 */
tigr.util.Dictionary.prototype.containsValue = function(val)
{
    var r = false;
    var i = this.getInternal();

    for (a in i)
    {
        if (i[ a ] == val)
        {
            r = true;
            break;
        }
    }

    return r;
}

/**
 * Returns a list of the keys in this map.
 * 
 * @return              the list of keys in this map.
 */
tigr.util.Dictionary.prototype.keys = function()
{
    var r = [];
    var i = this.getInternal();

    for (a in i)
    {
        r.push(a);
    }

    return r;
}

/**
 * Returns a list of the values in this map.
 *
 * @return              the list of values in this map.
 */
tigr.util.Dictionary.prototype.values = function()
{
    var r = [];
    var i = this.getInternal();

    for (a in i)
    {
        r.push(i[ a ]);
    }

    return r;
}

/**
 * Associates the specified value to the specified key in this map.
 * This will overwrite any existing key/value pair.
 *
 * @param   key         The key.
 * @param   val         The value.
 */
tigr.util.Dictionary.prototype.put = function(key, val)
{
    var i = this.getInternal();
    i[ key ] = val;
    this.size++;
}

/**
 * Returns the value that is mapped to the specified key.
 *
 * @param   key         The key.
 * @return              value mapped to the given key.
 */
tigr.util.Dictionary.prototype.get = function(key)
{
    var i = this.getInternal();
    return i[ key ];
}

/**
 * Deletes the key/value pair specified by the given key.
 *
 * @param   key         The key.
 */
tigr.util.Dictionary.prototype.remove = function(key)
{
    var i = this.getInternal();
    delete i[ key ];
}

/**
 * Returns the number of key/value pairs in this map.
 *
 * @return              the map size.
 */
tigr.util.Dictionary.prototype.size = function()
{
    return this.size;
}

// ------------------------------------------------------------------------- //

tigr.util.URLEncoder =
{
    encode : function(str)
    {
        var encoded = encodeURIComponent(str);

        // encodeURIComponent does not encode single quote characters.
        // -----------------------------------------------------------
        encoded = encoded.replace(/\'/g, '%27');

        return encoded;
    }
}

// ------------------------------------------------------------------------- //

tigr.util.URLDecoder =
{
    decode : function(str)
    {
        var decoded = decodeURIComponent(str);

        // decodeURIComponent does not decode + into a space.
        // --------------------------------------------------
        decoded = decoded.replace(/\+/g, ' ');

        return decoded;
    }
}

// ------------------------------------------------------------------------- //

tigr.util.Window =
{
    isChrome : function()
    {
        var result = $tigr.browser.webkit;
        if (result)
        {
            result = navigator.appVersion.indexOf(' Chrome/') > 0;
        }

        return result;
    },

    open : function(url)
    {
        var w;

        if (tigr.util.Window.isChrome())
        {
            w = window.open();

            w.opener = null;
            w.document.location = url;
        }
        else
        {
			if($tigr.browser.iPad)
			{
				// Pop-ups are not working in UIWebView
	            w = window.open(url, '_self');
			}
			else
			{
	            w = window.open(url, '_blank');
			}
        }

        // Check for popup blocker.
        // ------------------------
        // Firefox will return null for w if the user has set their preferences to not
        // notify the user of a popup request.
        if (w == null || typeof(w) == 'undefined')
        {
            alert('If you didn\'t see a window open you probably have a pop-up blocker enabled.\n\n' +
                  'Please disable this temporarily to allow this feature to work properly.');
        }

        return w;
    }
}

// ------------------------------------------------------------------------- //

tigr.util.StringBuffer = function(delimiter)
{
    this.delimiter = tigr.util.isUndefined(delimiter) ? '' : delimiter;
    this.idx = 0;
    this.arr = [];
}

tigr.util.StringBuffer.prototype.append = function(val)
{
    this.arr[ this.idx++ ] = val;
    return this;
}

tigr.util.StringBuffer.prototype.toString = function()
{
    return this.arr.join(this.delimiter);
}

tigr.util.StringBuffer.prototype.clear = function()
{
    this.arr = [];
    this.idx = 0;
}

// ------------------------------------------------------------------------- //

tigr.util.SearchEngineNames =
{
    GOOGLE    : 'GOOGLE',
    YAHOO     : 'YAHOO',
    MICROSOFT : 'MICROSOFT',
    ASK       : 'ASK',
    AOL       : 'AOL'
}

tigr.util.SearchEngine = function(name)
{
    this.name = name;
}

tigr.util.SearchEngine.prototype.createURL = function(keywords, pageNum, numResults)
{
    return null;
}

tigr.util.GoogleEngine = function()
{
    tigr.util.SearchEngine.call(this, tigr.util.SearchEngineNames.GOOGLE);
}

tigr.util.GoogleEngine.prototype = new tigr.util.SearchEngine(inheriting);

tigr.util.GoogleEngine.prototype.createURL = function(keywords, pageNum, numResults)
{
    var sb = new tigr.util.StringBuffer();

    sb.append('http://www.google.com/search?q=')
            .append(tigr.util.URLEncoder.encode(keywords))
            .append('&num=')
            .append(numResults)
            .append('&start=')
            .append(( ( pageNum * numResults ) - numResults ))
            .append('&yosrc=1');

    return sb.toString();
}

tigr.util.BingEngine = function()
{
    tigr.util.SearchEngine.call(this, tigr.util.SearchEngineNames.MICROSOFT);
}

tigr.util.BingEngine.prototype = new tigr.util.SearchEngine(inheriting);

tigr.util.BingEngine.prototype.createURL = function(keywords, pageNum, numResults)
{
    var sb = new tigr.util.StringBuffer();

    sb.append('http://www.bing.com/search?q=')
            .append(tigr.util.URLEncoder.encode(keywords))
            .append('&first=')
            .append(( ( pageNum * numResults ) - numResults + 1 ))
            .append('&yosrc=1');

    return sb.toString();
}

tigr.util.YahooEngine = function()
{
    tigr.util.SearchEngine.call(this, tigr.util.SearchEngineNames.YAHOO);
}

tigr.util.YahooEngine.prototype = new tigr.util.SearchEngine(inheriting);

tigr.util.YahooEngine.prototype.createURL = function(keywords, pageNum, numResults)
{
    var sb = new tigr.util.StringBuffer();

    sb.append('http://search.yahoo.com/search?p=')
            .append(tigr.util.URLEncoder.encode(keywords))
            .append('&n=')
            .append(numResults)
            .append('&b=')
            .append(( ( pageNum * numResults ) - numResults + 1 ))
            .append('&yosrc=1');

    return sb.toString();
}

tigr.util.AskEngine = function()
{
    tigr.util.SearchEngine.call(this, tigr.util.SearchEngineNames.ASK);
}

tigr.util.AskEngine.prototype = new tigr.util.SearchEngine(inheriting);

tigr.util.AskEngine.prototype.createURL = function(keywords, pageNum, numResults)
{
    var sb = new tigr.util.StringBuffer();

    sb.append('http://www.ask.com/web?q=')
            .append(tigr.util.URLEncoder.encode(keywords))
            .append('&page=')
            .append(pageNum)
            .append('&yosrc=1');

    return sb.toString();
}

tigr.util.AolEngine = function()
{
    tigr.util.SearchEngine.call(this, tigr.util.SearchEngineNames.AOL);
}

tigr.util.AolEngine.prototype = new tigr.util.SearchEngine(inheriting);

tigr.util.AolEngine.prototype.createURL = function(keywords, pageNum, numResults)
{
    var sb = new tigr.util.StringBuffer();

    sb.append('http://search.aol.com/aol/search?query=')
            .append(tigr.util.URLEncoder.encode(keywords))
            .append('&page=')
            .append(pageNum)
            .append('&yosrc=1');

    return sb.toString();
}

tigr.util.SearchEngineManager =
{
    isInit  : false,
    engines : null,

    init : function()
    {
        if (this.isInit)
            return;

        this.engines = new tigr.util.Dictionary();
        this.engines.put(tigr.util.SearchEngineNames.GOOGLE, new tigr.util.GoogleEngine());
        this.engines.put(tigr.util.SearchEngineNames.YAHOO, new tigr.util.YahooEngine());
        this.engines.put(tigr.util.SearchEngineNames.MICROSOFT, new tigr.util.BingEngine());
        this.engines.put(tigr.util.SearchEngineNames.ASK, new tigr.util.AskEngine());
        this.engines.put(tigr.util.SearchEngineNames.AOL, new tigr.util.AolEngine());
    },

    createURL : function(engine, keywords, pageNum, numResults)
    {
        var url = null;
        var se = this.engines.get(engine);

        if (se)
            url = se.createURL(keywords, pageNum, numResults);

        return url;
    }
}

tigr.util.SearchEngineManager.init();

// ------------------------------------------------------------------------- //

tigr.util.UUID =
{
    newUUID : function()
    {
        // Credit goes to Robert Kieffer's Math.uuid.js
        // http://www.broofa.com
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c)
        {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }
};

/*
 * Function used to return which type of widget this is
 * So underlying implementations know which one to use
*/
tigr.util.getWidget = function()
{
    if( yolink.cloud.Toolbar !== undefined )
    {
        return yolink.cloud.Toolbar;
    }
    else if( yolink.cloud.Embed !== undefined ) 
    {
        return yolink.cloud.Embed;
    }
    else if( yolink.cloud.Form !== undefined )
    {
        return yolink.cloud.Form;
    }

}
/*
 * Used to determine if the data is json data
 * 
 * @param  data    The data to check can be an object or string
 * @return boolean true if it is json data false if it is not
 */
tigr.util.isJSON = function( data )
{
    var isJson = false;
    try
    {
        $tigr.parseJSON( data );
        isJson = true; 
    } 
    catch(cause)
    {
        isJson = false;
    }
        return isJson;
}


if (!tigr) var tigr = {};
if (!tigr.ajax) tigr.ajax = {};

// ----------------------------------------------------------------------------

// Convert browser version to float.
$tigr.browser.version = parseFloat($tigr.browser.version);

tigr.ajax.getVersion = function(vstr)
{
    var ver;
    var nav = navigator.userAgent;
    var idx = nav.indexOf(vstr);

    if (idx != -1)
    {
        var str = nav.substring(idx + vstr.length + 1);
        ver     = parseFloat(str);
    }

    return ver;
}

// Returns true if this is a non-IE modern browser that supports direct
// cross-domain GET/POST calls.
tigr.ajax.isModernBrowser = function()
{
    var ret = false;

    if ($tigr.browser.safari || $tigr.browser.chrome || $tigr.browser.mozilla || $tigr.browser.iPad)
    {
        ret = ($tigr.browser.safari && $tigr.browser.version >= 4) ||
              ($tigr.browser.chrome && $tigr.browser.version >= 5) ||
   	      ($tigr.browser.mozilla && $tigr.browser.version >= 3.5) ||
	      ($tigr.browser.iPad);
    }

    return ret;
}

// $tigr.browser.chrome does not exist in jQuery.
$tigr.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
if ($tigr.browser.chrome)
{
    // Safari is always set to true for chrome.
    $tigr.browser.safari  = false;
    $tigr.browser.version = tigr.ajax.getVersion('Chrome');
}

// Convert version number for some of the browsers because they use either
// the webkit or gecko version numbers.  Hard to do comparisons on those.
if ($tigr.browser.safari)
{
    $tigr.browser.version = tigr.ajax.getVersion('Version');
}

if ($tigr.browser.mozilla)
{
    $tigr.browser.version = tigr.ajax.getVersion('Firefox');
}

// Returns the name of the current browser.
// We use constants here so that the values are not dependent on user-agent.
tigr.ajax.getBrowserName = function()
{
    var b = 'unknown';

    if ($tigr.browser.msie)
        b = 'MSIE';
    else
    if ($tigr.browser.mozilla)
        b = 'FIREFOX';
    else
    if ($tigr.browser.safari)
        b = 'SAFARI';
    else
    if ($tigr.browser.chrome)
        b = 'CHROME';

    return b;
}

// ----------------------------------------------------------------------------

// Parse Flash version.
tigr.ajax.getFlashVersion = function()
{
    var ver = '0,0,0';

    // Test IE first.
    try
    {
        var ao = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');

        try
        {
            // Don't crash the user's IE browser if they have a very old version of Flash.
            ao.AllowScriptAccess = 'always';

            // OK, we're greater than 6.
            ver = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version')
                                                                    .replace(/\D+/g, ',')
                                                                    .match(/^,?(.+),?$/)[1];
        }
        catch (e)
        {
            ver = '6,0,0';
        }
    }
    // Non-IE browsers.
    catch (e)
    {
        try
        {
            if (navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin)
            {
                ver = (navigator.plugins["Shockwave Flash 2.0"] || 
                       navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",")
                                                            .match(/^,?(.+),?$/)[1]
            }
        }
        catch (e) {}
    }

    return ver;
}


/*
 * Detects the flash and the minimum version that is required. 
 * Right now we need a minimum of v9, but tests have shown that 9.0.45 does not work very well
 * for IE. we get a nice error 2032 and it will fail until a newer version of flash is used. 
 * But we have not required a minimum of version 10 just yet. Need to test on this further
 */
tigr.ajax.isFlashPresent = tigr.ajax.getFlashVersion().split(',').shift() >= 9;

// ----------------------------------------------------------------------------

tigr.ajax.ResultHandler =
{
    fn       : null,
    fnError  : null,
    isEscaped: false,
    handleResult : function(data)
    {
        with (tigr.ajax)
        {
            if (ResultHandler.isEscaped)
            {
                data = unescape(typeof(data) == 'object' ? data.data : data);
            }

            ResultHandler.fn(data);
        }
    },

    handleError : function(err)
    {
        with (tigr.ajax)
        {
            alert( 'Oops, we are unable to process your request' );
            if (ResultHandler.fnError)
            {
                ResultHandler.fnError(err);
            }
        }
    }
}


// ----------------------------------------------------------------------------

$tigr(document).ready(function()
        {
            // Protect in case this file gets loaded multiple times.
            if (!($tigr('#yo_xd_conn').exists()))
            {
                var a = [];
                var i = 0;

                if ($tigr.browser.msie)
                {
                    a[i++] = '<object id="yo_xd_conn" width="0" height="0" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
                    a[i++] = 'data="'+getYoProp('server')+'/yolinklite/flash/XDHttpConnection.swf" type="application/x-shockwave-flash" >';
                    a[i++] = '<param name="movie" value="'+getYoProp('server')+'/yolinklite/flash/XDHttpConnection.swf"/>';
                    a[i++] = '<param name="allowscriptaccess" value="always"/>';
                    a[i++] = '</object>';
                }
                else
                {
                    a[i++] = '<object id="yo_xd_conn" width="0" height="0" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
                    a[i++] = 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0">';
                    a[i++] = '<embed src="'+getYoProp('server')+'/yolinklite/flash/XDHttpConnection.swf" allowscriptaccess="always" ';
                    a[i++] = 'width="0" height="0" type="application/x-shockwave-flash" name="yo_xd_conn" swliveconnect="true"/>';
                    a[i++] = '</object>';
                }

                $tigr(document.body).append($tigr(a.join('')));
            }
        });

/**
* remove flash div so that it will be loaded on each page load.
*/
$tigr(window).unload(function() {
  $tigr('#yo_xd_conn_div').remove();
});

// ----------------------------------------------------------------------------

// Create a new .getCSS function analogous to the .getScript function.
(function($tigr) {
    $tigr.getCSS = function(url, media)
    {
        $tigr(document.createElement('link')).attr({
                href : url,
                media: media || 'screen',
                type : 'text/css',
                rel  : 'stylesheet'
            }).appendTo('head');
    }
})($tigr);

// Cross-domain GET request.
// Usage:
//     $tigr.xget({url:'http://blah.com/hello.html', success:myObj.myFunction})
//
// The success function has the form:
//
//     function(data)
(function($tigr) {
    $tigr.xget = function(props)
    {
        tigr.ajax.ResultHandler.fn = props.success;
        var useAjax= true;

        // Flash...
        if (tigr.ajax.isFlashPresent)
        {
            var id    = 'yo_xd_conn';
            var flash = $tigr.browser.msie ? document.getElementById(id) : document[id];

            if (flash && flash.load)
            {
                // ActionScript does not allow HTTP headers in a GET request.
                if (props.hasOwnProperty('headers'))
                {
                    $tigr.xpost(props);
                }
                else if(props.use != null && props.use == 'parameterscallback')
                {
                     flash.loadparamargs('GET', props.url, null, null,props.success, (props.error)?props.error :'tigr.ajax.ResultHandler.handleError', props.successargs);
                }
                else
                {
                    tigr.ajax.ResultHandler.isEscaped = true;
                    flash.load(
                        {
                            url    : props.url,
                            type   : 'GET',
                            success: 'tigr.ajax.ResultHandler.handleResult',
                            browser: tigr.ajax.getBrowserName()
                        });
                }

                useAjax = false;
            }
        }

        // AJAX...
        if (useAjax)
        {
            var isSameDomain = tigr.util.isSameDomain(props.url);
            var url          = [];
            var i            = 0;

            url[i++] = props.url;
            if (!isSameDomain && window.XDomainRequest == undefined && !tigr.ajax.isModernBrowser ())
            {
                var proxyindex = props.url.indexOf("proxy-page");
                if(proxyindex >= 0)
                {
                   url[0] = props.url.substring(0, proxyindex)+"proxy-page.jsonp"+props.url.substring(proxyindex+"proxy-page".length);
                 }
                else
                {
                    url[i++] = (props.url.indexOf('?') == -1 ? '?' : '&');
                    url[i++] = 'o=jsonp&oe=UTF-8';
                }
            }

            url = url.join('');

            if (isSameDomain)
            {
                $tigr.ajax(
                    {
                        url     : url,
                        cache   : false,
                        success : function(data, tstatus, xhr)
                        {
                            tigr.ajax.ResultHandler.handleResult(xhr.responseText);
                        }
                    });
            }
            else
            if (window.XDomainRequest)
            {
                if (url.indexOf('cloud.yolink.com/yolinklite/html/gdocs.html')    != -1 ||
                    url.indexOf('cloud.yolink.com/yolinklite/html/bookmark.html') != -1 ||
                    url.indexOf('cloud.yolink.com/yolinklite/html/social.html')   != -1)
                {
                    url = getYoProp('server')+'/yolink/xget?o=original&u=' + encodeURIComponent(url);
                }

                var req = new XDomainRequest();
                req.open('get', url);
                 req.onload = function()
                    {
                       
                        if(props.use != null && props.use == 'parameterscallback')
                        {
                            var succ = eval(props.success);
                            succ(props.successargs,req.responseText);
                        }
                        else
                        {
                             tigr.ajax.ResultHandler.handleResult(req.responseText);
                        }

                        }

                req.send();
            }
            else if (tigr.ajax.isModernBrowser ())
            {
                $tigr.ajax(
                {
                    url     : url,
                    cache   : false,
                    props : props,
                    success : function(data, tstatus, xhr)
                    {

                         if(props.use != null && props.use == 'parameterscallback')
                        {
                             var succ = eval(props.success);
                              succ(props.successargs,xhr.responseText);
                        }
                        else
                        {
                            tigr.ajax.ResultHandler.handleResult(xhr.responseText);
                        }
                    }
                });

            }

            else
            {
                var callback = (props.jsonpsuccess != null )? props.jsonpsuccess:'tigr.ajax.ResultHandler.handleResult';

                $tigr.ajax(
                    {
                        url           : url,
                        cache         : false,
                        dataType      : 'jsonp',
                        jsonpCallback : callback
                    });
            }
        }
    }
})($tigr);

// Cross-domain POST request.
// Usage:
//     $tigr.xpost({url:'http://blah.com/hello',
//              headers:{one:'o', two:'t'},
//              success: myObj.myFunc,
//              error: myObj.myError,
//              data:encodeURIComponent(myData)});
//
//     Note that the values in the headers must already be URL encoded.
//
//     The functions for success and error have the form:
//
//         function(data)
(function($tigr) {
    $tigr.xpost = function(props)
    {
        tigr.ajax.ResultHandler.fn = props.success;
        var useAjax = true;

        // Flash...
        if (tigr.ajax.isFlashPresent)
        {
            var id    = 'yo_xd_conn';
            var flash = $tigr.browser.msie ? document.getElementById(id) : document[id];

            if (flash && flash.load)
            {
                tigr.ajax.ResultHandler.isEscaped = true;
                if(props.use != null && props.use == 'parameterscallback')
                {
                     flash.loadparamargs('POST', props.url,props.hasOwnProperty('contentType') ? props.contentType : 'application/x-www-form-urlencoded',props.data,'tigr.ajax.ResultHandler.handleResult', 'tigr.ajax.ResultHandler.handleError',props.successargs);
                }
                else
                {
                    flash.load(
                        {
                            url        : props.url,
                            type       : 'POST',
                            headers    : props.hasOwnProperty('headers') ? props.headers : {},
                            contentType: props.hasOwnProperty('contentType') ? props.contentType : 'application/x-www-form-urlencoded',
                            data       : props.data,
                            success    : 'tigr.ajax.ResultHandler.handleResult',
                            browser    : tigr.ajax.getBrowserName()
                        });
                }

                useAjax = false;
            }
        }

        // NOTE: Occasionally on IE the flash file will load, but the load() function
        //       is not exported.  In these cases, the function will never export until
        //       the page is refreshed vai CTRL-R.  For IE 8 the work-around is to use 
        //       XDomainRequest.

        // AJAX...
        if (useAjax)
        {
            var url  = [];
            var i    = 0;

            url[i++] = props.url;
            url[i++] = (props.url.indexOf('?') == -1 ? '?' : '&');
            // window.XDomainRequest is a construct of IE8 anything less and this will yield undefined
            // therefore the fallback is to resort to jsonp.  Since jsonp can't handle POSTS we pass in the data
            // into the url parameter.  *Note we will need to investigate puttig the data in the header or
            // some sort of transactional get, so it can handle jsonp data as a fallback in the event that
            // flash fails to load, is the wrong version, or is un-available
            // --------------------------------------------------------------------------
            if( window.XDomainRequest == undefined  && !tigr.ajax.isModernBrowser ())
            {
                url[i++] = 'o=jsonp&oe=UTF-8';
                url[i++] = '&data=';
                url[i++] = encodeURIComponent(props.data);
            }
            else
            {
                url[i++] = 'xdom=y';
            }

            if (props.hasOwnProperty('headers'))
            {
                var h;
                for (h in props.headers)
                {
                    url[i++] = '&';
                    url[i++] = h;
                    url[i++] = '=';
                    url[i++] = encodeURIComponent(props.headers[h]);
                }
            }

            url = url.join('');

            if (window.XDomainRequest)
            {
                var req = new XDomainRequest();
                req.open('post', url);
                req.onload = function()
                {
                    tigr.ajax.ResultHandler.handleResult(req.responseText);
                };
                req.send(props.data);
            }
            else if(tigr.ajax.isModernBrowser ())
            {
               
                var req = new XMLHttpRequest();
                req.open('POST', url);
                req.onreadystatechange = function()
                {
                    if(req.readyState == 4 && req.status == 200)
                    {
                           tigr.ajax.ResultHandler.handleResult(req.responseText);
                    }
                }
                req.send(props.data);
            
            }
            else
            {
                $tigr.ajax(
                    {
                        url           : url,
                        cache         : false,
                        processData   : false,
                        jsonpCallback : 'tigr.ajax.ResultHandler.handleResult',               
                        error         : function( data )
                                        {
                                            tigr.ajax.ResultHandler.handleError(data);
                                        },             
                        type          : 'POST',
                        dataType      : 'jsonp'
                    });
            }
        }
        // Otherwise you're fooked :-)
    }
})($tigr);

// ========== start trash.js ==========
Trash =
{
    // Ensures that all 'More Results Available' links are valid.
    // If there are no more chunks under these links, then remove them.
    ensureMoreResultsLinks : function()
    {
        $tigr('a[name=yo_more_results]:visible').each(function(idx, val)
                {
                    var tbl = $tigr('#yo_ht_' + $tigr(this).attr('idx'));
                    if (tbl && ($tigr('input[name=chunk-checkbox][deleted=false]', tbl).size() == 0))
                    {
                        $tigr(this).hide();
                    }
                });
    },

    // Determine if the 'Check All' checkbox should be checked or not.
    ensureCheckAllCheckbox : function()
    {
        var total   = $tigr('input[name=chunk-checkbox][deleted=false]').size();
        var checked = $tigr('input[name=chunk-checkbox][deleted=false]:checked').size();

        $tigr('#check_all').attr('checked', ((total > 0) && (total == checked)));
    },

    // Remove all parent <div>s (class="yo_r") if there are no more chunks.
    ensureNonEmptyParents : function()
    {
        $tigr('.yo_r').each(function(idx, val)
                {
                    if ($tigr('input[name=chunk-checkbox][deleted=false]', $tigr(this)).size() == 0)
                    {
                        $tigr(this).remove();
                    }
                });
    },

    // Deletes all selected chunks.
    remove : function()
    {
        $tigr('input[name=chunk-checkbox]:checked').each(function(idx, val)
                {
                    $tigr(this).attr('deleted', 'true').attr('checked', false);
                    $tigr('#' + $tigr(this).attr('par')).hide();                        // hide the parent
                });

        Trash.ensureMoreResultsLinks();
        Trash.ensureCheckAllCheckbox();
        Trash.ensureNonEmptyParents();
    },

    // Deletes all results regardless of their selection status.
    removeAll : function()
    {
        $tigr('.yo_r').remove();

        var checkAll = $tigr('#check_all');
        if (checkAll)
        {
            checkAll.attr('checked', false);
        }
    }
}
// ========== end trash.js ==========

// ========== start checkbox.js ==========
Checkbox =
{
    resetResultCheckBoxes : function()
    {
      $tigr('input[name=result-checkbox]').each(function(index,value){
             value.checked = false;
      });
    },

    onResultCheckBoxClick : function(inputparent)
    {
       var checked = inputparent.checked;
       $tigr('input[name=chunk-checkbox][deleted=false][par='+inputparent.id+']').each(
                    function(index, value)
                    {
                        value.checked = checked;
                    });

        this.onClick(inputparent);
    },
    onChunkCheckBoxClick : function(input)
    {
        var parentcheckid = $tigr(input).attr("par");
        if(parentcheckid != null)
        {
            var total   = $tigr('input[name=chunk-checkbox][deleted=false][par='+parentcheckid+']').size();
            var checked = $tigr('input[name=chunk-checkbox][deleted=false][par='+parentcheckid+']:checked').size();
            $tigr('input[name=result-checkbox][id='+parentcheckid+']').attr('checked', ((total > 0) && (total == checked)));
        }
        this.onClick(input);
    },
    onClick : function(input)
    {
        var total   = $tigr('input[name=chunk-checkbox][deleted=false]').size();
        var checked = $tigr('input[name=chunk-checkbox][deleted=false]:checked').size();

        $tigr('#check_all').attr('checked', ((total > 0) && (total == checked)));
    },

    selectAll : function(input)
    {
        $tigr('input[name=chunk-checkbox][deleted=false]').attr('checked', $tigr(input).attr('checked'));
    }
}
// ========== end checkbox.js ==========
// ------------------begin search.js--------
function toggle(id)
{
    $tigr('#m' + id).css("display", "none");
    $tigr('#h' + id).css("display", "block");
}

function check(checkbox, checked, inherited)
{
    checkbox.checked = checked;
    checkbox.disabled = checked && inherited;
}

function checkall(checkbox)
{
    var checked = checkbox.checked;
    $tigr("input[type='checkbox']").each(
            function(index, value)
            {
                check(value, checked, isInherited(value));
            });
}

function isInherited(checkbox)
{
    var inherited = $tigr(checkbox).attr('inherited');

    return inherited && ( inherited == 'true' );
}

function rcheck(checkbox)
{
    var checked = checkbox.checked;
    $tigr('.' + checkbox.id).each(
            function(index, value)
            {
                check(value, checked, isInherited(value));
            });

    if (!checked)
    {
        $tigr("#check_all").each(
                function(index, value)
                {
                    value.checked = false;
                });

    }
}

function img_mouseover(img)
{
    var src = img.src;
    var end = src.substring(src.length - 12);

    if (end == "hover311.png")
    {
        img.src = src.substring(0, src.length - 12) + "311.png";
    }
    else
    {
        img.src = src.substring(0, src.length - 7) + "hover311.png";
    }
}

function checkSelectAll()
{
    var checked = $tigr('input[name=chunk-checkbox]:checked');
    if (checked.length == 0)
    {
        var result = confirm('No results selected. Select all?');
        if (result)
        {
            $tigr('input[name=chunk-checkbox]').each(
                    function(index, value)
                    {
                        value.checked = true;
                    });

        }

        return result;
    }
    else
    {
        return true;
    }
}


Popup =
{
    validresults : false,
    showdialog : true,
    popupdialoghtml : "<div class=\"modalBackground\"><div id=\"popupHeaderContainer\" class=\"popupHeaderContainer\" style=\"display:none;\"> \n" +
                      "<map name=\"closemap\"> \n" +
                      "<area\n" +
                      "  href=\"javascript:Popup.closeMsgDialog();\" alt=\"close\" title=\"close\"\n" +
                      "  shape=\"RECT\" COORDS=\"461,168,474,180\"/> \n" +
                      "</map> \n" +
                      "<table style=\"table-layout:fixed;width:511;border:0px none black;padding:0px;\" > \n" +
                      "<tr style=\"border:0 none;padding:0px;margin:0px;\"> \n" +
                      "<td style=\"border:0px solid black;padding:0px;margin:0px;\"> \n" +
                      "<input type=\"checkbox\" id=\"checkboxlocation\" onclick=\"Popup.setUserPrefOnMsgDialog(this)\"></input> \n" +
                      "<div style='margin-top:12px;margin-bottom:12px;margin-left:12px;margin-right:15px;'><img  click=\"javascript:Popup.closeMsgDialog();\" src=\""+getYoProp('server')+"/search/css/images/cloud_popup.png\" border=\"0\" width=\"511\" height\"220\" usemap=\"#closemap\"/></div> \n" +
                      "</td> \n" +
                      "</tr> \n" +
                      "</table>\n" +
                      "</div></div>",


    addPopupDialog : function()
    {
        if (this.validresults == true && this.showdialog == true)
        {
            try
            {
                var popupdiv = document.getElementsByTagName('body')[0];
                $tigr(popupdiv).append(this.popupdialoghtml);
                this.showMsgDialog();

            }
            catch (e)
            {

            }
        }
    },

    showMsgDialog:function ()
    {
        var cookie = tigr.util.readCookie("cloudyolinkresultsmsgdlg");
        if (!cookie)
        {
            var popupmain = $tigr('#popupHeaderContainer');
            var widthheight = tigr.util.getWindowWidthHeight();
            height = Math.floor(widthheight.height / 3);
            width = Math.floor(widthheight.width / 3);
            $tigr(popupmain).css('margin-left', width);
            $tigr(popupmain).css('top', height);
            $tigr(popupmain).fadeIn('slow');
        }
    },
    closeMsgDialog:function()
    {
        var popupmain = $tigr('#popupHeaderContainer');
        $tigr(popupmain).fadeOut('slow');

    },

    setUserPrefOnMsgDialog:function(inputcheck)
    {
        if (inputcheck.checked)
        {
            tigr.util.createCookie("cloudyolinkresultsmsgdlg", "dontshow", 365);
        }
        else
        {
            tigr.util.deleteCookie("cloudyolinkresultsmsgdlg");
        }
    }


}

function xmlify(data)
{
    if ($tigr.browser.msie)
    {
        // Workaround.
        // -----------
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

        xmlDoc.async = "false";
        xmlDoc.loadXML(data);

        data = xmlDoc;
    }

    return data;
}

// ----------------------------------------------------------------------------
// common state
// ----------------------------------------------------------------------------
Context =
{
    getKeywords : function()
    {
        var widget   = tigr.util.getWidget();
        var keywords = widget.getKeywords();
        if( typeof keywords == undefined )
        {
            // fallback to the default keyword search
            // --------------------------------
            keywords = $tigr('input[name="search"]').attr('value');
        }
        return keywords;   
    },

    getSelectedResults : function()
    {
        var b = new tigr.util.StringBuffer();

        b.append('<rsetdata op="link">');

        $tigr('.r_f').each(
                function(index, value)
                {
                    var checked = $tigr('input:checkbox:checked', value);
                    if (checked.size() > 0)
                    {
                        var title   = $tigr(value).attr('title');
                        var table   = $tigr(checked[0]).closest('table');
                        var url     = $tigr(table).attr('u');

                        b.append('<rset tle="');
                        b.append(title);
                        b.append('" pgurl="');
                        b.append(url);

                        var license = $tigr(value).attr('license');
                        if( license )
                        {
                            b.append( '" lic="' );
                            b.append( license );
                        }

                        b.append('">');

                        var len = checked.size();
                        for (var i = 0; i < len; ++i)
                        {
                            var checkbox = checked[ i ];
                            if (isInherited(checkbox))
                            {
                                var par = $tigr(checkbox).closest('tr');
                                var text = $tigr('.yo_preview', par);
                                b.append('<r>');
                                b.append($tigr(text).html());
                                b.append('</r>');
                            }
                        }

                        b.append('</rset>');
                    }
                });

        b.append('</rsetdata>');

        return b.toString();
    },

    getCookie : function(name)
    {
        var cookie = document.cookie.split("; ");
        for (var i = 0; i < cookie.length; i++)
        {
            var crumb = cookie[i].split("=");
            if (name == crumb[0])
            {
                return unescape(crumb[1]);
            }
        }

        return null;
    },

    hasMultipleSelections : function()
    {
        var results = 0;

        $tigr('.r_f').each(
                function(index, value)
                {
                    var checked = $tigr('input[type="checkbox"]:checked', value);
                    if (checked.length > 0)
                    {
                        ++results;
                    }
                });

        return results > 1;
    },

// Returns a new UUID.
// Function is used for both client/product IDs.
    getClientID : function()
    {
        var cid = this.getCookie('cid');

        if (!cid)
        {
            cid = tigr.util.UUID.newUUID();
            var d = new Date(2161, 6, 4, 0, 0, 0, 0);
            document.cookie = 'cid=' + cid + '; expires=' + d.toUTCString();
        }

        return cid;
    },

    getDefaultTitle : function()
    {
        var title = document.title;

        if (!this.hasMultipleSelections())
        {
            $tigr('.r_f').each(function(idx, val)
            {
                var checked = $tigr('input[type="checkbox"]:checked', val)
                if (checked.length > 0)
                {
                    title = $tigr(val).attr('title');
                    return false;
                }
            });
        }
        try{
	if(title.length == 0)
	{
		title  = window.location.href + ' - ' + Context.getKeywords() ;		
	}
	}catch(e){ 
		title = 'Please enter a title'
	}

        return title;
    },

    getURL : function()
    {
        var result;
        if (this.hasMultipleSelections())
        {
            result = document.location.href;
        }
        else
        {
            $tigr('.r_f').each(
                    function(index, value)
                    {
                        var checked = $tigr('input[type="checkbox"]:checked', value);
                        if (checked.length > 0)
                        {
                            result = $tigr(checked[0]).closest('table').attr('u');
                        }
                    });
        }

        return result;
    }
}
Email =
{
    isInitialized : false,
    isDownloaded  : false,
    doc           : null,

    init : function(doc)
    {
        this.doc = doc;

        if (!this.isInitialized)
        {
            var that = this;

            $tigr('#email_dialog').dialog
                    (
                    {
                        zIndex: 999988,
                        autoOpen   : true,
                        modal      : true,
                        open       : function()
                        {
                            that.clear();
                        },
                        resizeable : false,
                        buttons    : { 'Cancel' : function(event)
                        {
                            that.cancel(event);
                        }, 'Send' : function(event)
                        {
                            that.send(event);
                        } }
                    }
                            );

            $tigr('#email_dialog').dialog();

            this.isInitialized = true;
        }
    },

    open : function(title, url)
    {
        $tigr('#email_dialog').dialog('option', 'chunkurl', url);
        $tigr('#email_dialog').dialog('option', 'chunktitle', title);
        $tigr('#email_dialog').dialog('open');
    },

    clear : function()
    {
        $tigr('#email_errorMsg').addClass('emailError');
        $tigr('#fromName')[ 0 ].value = '';
        $tigr('#fromAddress')[ 0 ].value = '';
        $tigr('#toAddress')[ 0 ].value = '';
        $tigr('#personalNote')[ 0 ].value = '';
    },

    cancel : function()
    {
        $tigr('#email_dialog').dialog('close');
    },

    isValidEmail : function(addr)
    {
        var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
        return pattern.test(addr);
    },

// POST callback function.
    onResult : function(result)
    {
        // No return data for email.
    },

    send : function()
    {
        var doc = Email.doc;
        $tigr('#email_errorMsg', doc).addClass('emailError');

        // Validate content.
        // -----------------
        var isValid = true;
        var errMsg = '';

        var name = $tigr('#fromName', doc)[ 0 ].value.trim();
        if (name.length == 0)
        {
            isValid = false;
            errMsg += 'Your name is missing.<br/>';
        }
        else
            if (name.indexOf('@') != -1)
            {
                isValid = false;
                errMsg += 'Name cannot contain the "@" sign.<br/>';
            }

        var from = $tigr('#fromAddress', doc)[ 0 ].value.trim();
        if (!Email.isValidEmail(from))
        {
            isValid = false;
            errMsg += 'Your email address is invalid.<br/>';
        }

        var to = $tigr('#toAddress', doc)[ 0 ].value;
        var addrs = to.split(',');
        var addErr = true;
        $tigr.each
                (
                        addrs,
                        function(index, value)
                        {
                            var val = value.trim();
                            if (addErr && !Email.isValidEmail(val))
                            {
                                isValid = false;
                                errMsg += 'The \'Send to\' email address is invalid.<br/>';
                            }
                        }
                        );

        if (!isValid)
        {
            $tigr('#email_errors', doc)[ 0 ].innerHTML = errMsg;
            $tigr('#email_errorMsg', doc).removeClass();

            return false;
        }

        var note = $tigr('#personalNote', doc)[ 0 ].value;

        // Content validated => send email content to server.
        // --------------------------------------------------
        var uri = $tigr('#email_dialog', doc).dialog('option', 'chunkurl');
        var title = $tigr('#email_dialog', doc).dialog('option', 'chunktitle');

        var payload = Context.getSelectedResults();
        var key = Context.getKeywords();

        $tigr.xpost(
        {
            url    :getYoProp('server')+'/yolink/snliteemailxml',
            headers:{oe     :'UTF-8',
                o      :'text/plain',
                sn     :'Email',
                k      :tigr.util.URLEncoder.encode(key),
                i      :Context.getClientID(),
                u      :Context.getClientID(),
                t      :tigr.util.URLEncoder.encode(title),
                url    :tigr.util.URLEncoder.encode(uri),
                from   :tigr.util.URLEncoder.encode(from),
                to     :tigr.util.URLEncoder.encode(to),
                comment:tigr.util.URLEncoder.encode(note),
                uname  :tigr.util.URLEncoder.encode(name)},
            contentType:'text/plain',
            success:Email.onResult,
            data   :payload
        });

        $tigr('#email_dialog', doc).dialog('close');
    }
}

Bookmark =
{
    isInitialized : false,
    result        : null,
    title         : null,
    isDownloaded  : false,
    anchor        : null,

    trim : function(str, collapse)
    {
        var str = (str) ? str.replace(/^\s+|\s+$/g, '') : '';

        // Replace all whitespace within the string with a single space.
        if (collapse)
        {
            str = str.replace(/\s{2,}/g, ' ');
        }

        return str;
    },

    clear : function()
    {
        $tigr('#bookmarkErrorMsg').text('');
        var title = $tigr('#bookmarkDialog').dialog('option', 'chunktitle');
        $tigr('#bookmarkTitle').val(title);
    },

    cancel : function(event)
    {
        $tigr('#bookmarkDialog').dialog('close');
    },

    ok : function(event)
    {
        // Validate that we have a non-empty title.
        // ----------------------------------------
        var url = $tigr('#bookmarkDialog').dialog('option', 'chunkurl');
        var title = this.trim($tigr('#bookmarkTitle').val(), true);

        if (title == '')
        {
            $tigr('#bookmarkErrorMsg').text('Title cannot be blank.');
            $tigr('#bookmarkErrorDiv').removeClass();

            return false;
        }

        var payload = Bookmark.result;
        var keyword = Context.getKeywords();

        $tigr('#bookmarkDialog').dialog('close');
        this.title = title;
        this.create(title, url, keyword, Context.getSelectedResults());
    },

    init : function(doc)
    {
        var that = Bookmark;

        if (!that.isInitialized)
        {
            $tigr('#bookmarkDialog').dialog
                    (
                    {
                        zIndex: 999988,
                        autoOpen  : false,
                        modal     : true,
                        open      : function()
                        {
                            that.clear();
                        },
                        resizable : false,
                        buttons   : { 'Cancel' : function(event)
                        {
                            that.cancel(event);
                        }, 'OK' : function(event)
                        {
                            that.ok(event);
                        } }
                    }
                            );

            $tigr('#bookmarkDialog').dialog();

            that.isInitialized = true;
        }
    },

    open : function(title, url)
    {
        $tigr('#bookmarkDialog').dialog('option', 'chunktitle', title);
        $tigr('#bookmarkDialog').dialog('option', 'chunkurl', url);
        $tigr('#bookmarkDialog').dialog('open');
    },

    onPageLoad : function(result)
    {
        if (result)
        {
            Bookmark.isDownloaded = true;

            $tigr(Bookmark.anchor).append(typeof(result) == 'object' ? result.data : result);
            $tigr(Bookmark.anchor).fadeIn('slow');
        }

        Bookmark.init(document, Context.getSelectedResults());
        Bookmark.open(Context.getDefaultTitle(), Context.getURL());
    },

    show : function(div)
    {
        this.anchor = div;
        if (!this.isDownloaded)
        {
            $tigr.xget({url:getYoProp('server')+'/yolinklite/html/bookmark.html', success:Bookmark.onPageLoad});
            this.isDownloaded = true;
        }
        else
        {
            Bookmark.onPageLoad();
        }
    },

    onResult : function(data)
    {
        var url = typeof(data) == 'object' ? data.data : data;
        if (url)
        {
            Bookmark.add(Bookmark.title, decodeURIComponent(url));
        }
    },

    create : function(title, url, keyword, payload)
    {
        $tigr.xpost(
        {
            url    :getYoProp('server')+'/yolink/snlitescxml',
            headers:{oe :'UTF-8',
                o  :'text/plain',
                sn :'bookmark',
                k  :tigr.util.URLEncoder.encode(keyword),
                i  :Context.getClientID(),
                u  :Context.getClientID(),
                e  :'UTF-8',
                t  :tigr.util.URLEncoder.encode(title),
                url:tigr.util.URLEncoder.encode(url)},
            contentType:'text/plain',
            success:Bookmark.onResult,
            data   :payload
        });
    },

    add : function(title, url)
    {
        alert('Shared page will be opened in a new tab or window. Please use ' + ( navigator.appVersion.indexOf('Mac') > 0 ? 'Command' : 'CTRL' ) + '+D to bookmark the page.');
        tigr.util.Window.open(url);
    }
}

Social =
{
    PAIR_DELIMITER  : ';',
    VALUE_DELIMITER : '::',
    isInitialized   : false,
    doc             : null,
    anchor          : null,
    isDownloaded    : false,

    init : function(doc)
    {
        if (!this.isInitialized)
        {
            $tigr('#share_dialog', doc).dialog
                    (
                    {
                        zIndex: 999988,
                        autoOpen   : true,
                        height     : 400,
                        width      : 310,
                        modal      : true,
                        resizeable : false,
                        buttons    : {'Close' : function()
                        {
                            $tigr('#share_dialog', doc).dialog('close');
                        }}
                    }
                            );

            $tigr('#share_dialog', doc).dialog();

            var that = this;
            $tigr('#share_mainTable', doc).click(function(event)
            {
                that.onClick(event);
            });

            this.doc = doc;
            this.isInitialized = true;
        }
    },

// jsonp callback function with the URL to open.
    onResult : function(data)
    {
        var url = typeof(data) == 'object' ? data.data : data;
        if (url)
        {
            //for easy bib, the response format from the server is
            //http://www.easybib.com/cite/form?data=[encoded JSON]
            //so  need to encode again  to keep the data parameter as the encoded JSON
            //--------------------------------------------------------------------------
            if (url.indexOf("easybib") > 0)
            {
                url = decodeURIComponent(url);
                var index = "http://www.easybib.com/cite/form?data=".length;
                var jsondata = url.substring(index, url.length);
                tigr.util.Window.open("http://www.easybib.com/cite/form?data=" + encodeURIComponent(jsondata));
            }
            else
            {
                tigr.util.Window.open(decodeURIComponent(url));
            }
        }
    },

// Post data when user clicks on a social share icon.
    onClick : function(event)
    {
        var name = event.target.getAttribute('socialname');
        var url = $tigr('#share_dialog').dialog('option', 'chunkurl');
        var title = $tigr('#share_dialog').dialog('option', 'chunktitle');
        var keyword = Context.getKeywords();
        var isGeneric = (name.toLowerCase() == 'email');

        $tigr('#share_dialog').dialog('close');

        if (!isGeneric)
        {
            var payload = Context.getSelectedResults();
            $tigr.xpost(
            {
                url    :getYoProp('server')+'/yolink/snlitescxml',
                headers:{oe :'UTF-8',
                    o  :'text/plain',
                    sn :name,
                    k  :tigr.util.URLEncoder.encode(keyword),
                    i  :Context.getClientID(),
                    u  :Context.getClientID(),
                    e  :'UTF-8',
                    t  :tigr.util.URLEncoder.encode(title),
                    url:tigr.util.URLEncoder.encode(url)},
                contentType:'text/plain',
                success:function (data)
                {
                    Social.onResult(data);
                },
                data   :payload});
        }
        else
        {
            Email.init(document);
            Email.open(title, url);
        }
    },

// jsonp callback after retrieving the social.html page.
    onPageLoad : function(result)
    {
        if (result)
        {
            Social.isDownloaded = true;

            $tigr(Social.anchor).append(typeof(result) == 'object' ? result.data : result);
            $tigr(Social.anchor).fadeIn('slow');
        }

        Social.init(document);
        Social.open();
    },

// Load social dialog ui.
    show : function(div)
    {
        this.anchor = div;
        if (!this.isDownloaded)
        {
            $tigr.xget({url:getYoProp('server')+'/yolinklite/html/social.html', success:Social.onPageLoad});
            this.isDownloaded = true;
        }
        else
        {
            Social.onPageLoad();
        }
    },

    sortList : function(a, b)
    {
        var aTuple = a.split(Social.VALUE_DELIMITER);
        var bTuple = b.split(Social.VALUE_DELIMITER);

        var res = 0;
        if (aTuple[ 1 ] < bTuple[ 1 ])
        {
            res = -1;
        }
        else
            if (aTuple[ 1 ] > bTuple[ 1 ])
            {
                res = 1;
            }

        return res;
    },

    onSocialList : function(result)
    {
        var xml = typeof(result) == 'object' ? result.data : result;
        var list = '';
        var that = Social;

        // in some cases flash fails to load and jsonpdata is returned
        // ---------------------------------------------
        if( tigr.util.isJSON( xml ) )
        {
            dom = $tigr.parseJSON(xml);
            $tigr(dom).each
                    (
                            function(idx, val)
                            {
                                list += val.type + that.VALUE_DELIMITER +
                                        val.name + that.VALUE_DELIMITER +
                                        val.icon + that.PAIR_DELIMITER;
                            }
                    );
        }
        // parse the regular xml version
        // ----------------------------
        else if (xml)
        {
            dom = xml;

            if (!window.DOMParser)
            {
                dom = new ActiveXObject('Microsoft.XMLDOM');
                dom.async = false;
                dom.loadXML(xml);
            }

            $tigr(dom).find('service').each
                    (
                            function()
                            {
                                list += $tigr(this).attr('type') + that.VALUE_DELIMITER +
                                        $tigr(this).find('name').text() + that.VALUE_DELIMITER +
                                        $tigr(this).find('icon').text() + that.PAIR_DELIMITER;
                            }
                            );
        }
        
        var ediv = $tigr('#share_emailDiv', that.doc);
        var sdiv = $tigr('#share_socialDiv', that.doc);
        var rdiv = $tigr('#share_researchDiv', that.doc);

        if (ediv.children().length == 0)
        {
            list = list.split(that.PAIR_DELIMITER);
            list.sort(that.sortList);

            $tigr.each
                    (
                            list,
                            function(index, value)
                            {
                                if (value.length > 0)
                                {
                                    var tuple = value.split(that.VALUE_DELIMITER);
                                    var div = null;

                                    switch (tuple[ 0 ].toLowerCase())
                                            {
                                        case 'email'    :
                                            div = ediv;
                                            break;

                                        case 'social'   :
                                            div = sdiv;
                                            break;

                                        case 'research' :
                                            div = rdiv;
                                            break;
                                    }

                                    if (div != null)
                                    {
                                        div.append($tigr('<div class="socialShare" socialname="' + tuple[ 1 ] + '">' +
                                                            '<img socialname="' + tuple[ 1 ] + '" class="socialImg" src="' + tuple[ 2 ] + '"/>' +
                                                            '<span class="socialSpan" socialname="' + tuple[ 1 ] + '">' + tuple[ 1 ] + '</span>' +
                                                            '</div>'));
                                    }
                                }
                            }
                        );

            $tigr('.socialSpan', that.doc).hover(function()
            {
                $tigr(this).addClass('hover');
            },
                    function()
                    {
                        $tigr(this).removeClass('hover');
                    });
            }

            $tigr('#share_dialog', that.doc).dialog('option', 'chunkurl', Context.getURL());
            $tigr('#share_dialog', that.doc).dialog('option', 'chunktitle', Context.getDefaultTitle());
            $tigr('#share_dialog', that.doc).dialog('open');
    },

    open : function()
    {
        $tigr.xget({url:getYoProp('server')+'/yolink/listshareservices?oe=UTF-8', success:Social.onSocialList});
        return true;
    }
}

var GoogleDocument = function( starred,
                               title,
                               resourceId,
                               modifiedDate,
                               longDate,
                               docType,
                               folderName,
                               iconURL )
{
    this.starred      = starred;
    this.title        = title;
    this.resourceId   = resourceId;
    this.modifiedDate = modifiedDate;
    this.longDate     = parseInt( longDate );
    this.docType      = docType;
    this.folderName   = folderName,
    this.iconURL      = iconURL;
};

var GoogleDocs =
{
    DOCS_INCREMENT : 5,
    isInitialized  : false,
    isDownloaded   : false,
    doc            : null,
    docList        : null,
    docListOrig    : null,
    selectedDoc    : null,
    startIndex     : 0,
    endIndex       : 0,
    idleTimeout    : null,
    action         : 'new',
    docType        : null,
    anchor         : null,

    init : function( doc )
    {
        var that = this;

        if( !that.isInitialized )
        {
            $tigr( '#gdocs', doc ).dialog
                (
                    {
						zIndex: 999988,
						autoOpen  : true,
                        width     : 400,
                        modal     : true,
                        resizable : false,
                        open      : GoogleDocs.onOpen,
                        buttons   : { 'Cancel' : GoogleDocs.onCancel, 'OK' : GoogleDocs.onOK }
                    }
                );

            $tigr( '#gdocs_errorDialog', doc ).dialog
                (
                    {
						zIndex: 999988,
                        autoOpen  : false,
                        height    : 170,
                        width     : 400,
                        modal     : false,
                        resizable : false,
                        buttons   : { "Ok": function() { $tigr(this).dialog("close"); } }
                    }
                );

            that.isInitialized = true;

            // Bind click event to the document list table.
            // --------------------------------------------
            $tigr( '#gdocs_docListTbl', doc ).click( function( event ) { that.onTableClick( event ); } );

            // Bind the keyup for Google Docs search.
            // --------------------------------------
            $tigr( '#gdocs_search', doc ).unbind( 'keyup', function( event ) { that.onKeyUp( event ); } );
            $tigr( '#gdocs_search', doc ).bind( 'keyup', function( event ) { that.onKeyUp( event ); } );
        }
    },

    onPageLoad : function(result)
    {
        if (result)
        {
            GoogleDocs.isDownloaded = true;

            $tigr(GoogleDocs.anchor).append(typeof(result) == 'object' ? result.data : result);
            $tigr( '#gdocs_appendPanel' ).addClass( 'invisible' );            
            $tigr(GoogleDocs.anchor).fadeIn('slow');
        }

        GoogleDocs.init(document);
        GoogleDocs.open();
    },

    show : function(div)
    {
        this.anchor = div;
        if( !GoogleDocs.isDownloaded )
        {
            $tigr.xget({url:getYoProp('server')+'/yolinklite/html/gdocs.html', success:GoogleDocs.onPageLoad});
        }
        else
        {
            GoogleDocs.onPageLoad();
        }
    },

    hide : function(div)
    {
        $tigr(div).fadeOut( 'slow' );
    },

    setDocType : function( event )
    {
        var g = GoogleDocs;

        if( $tigr.browser.msie )
        {
            g.docType = $tigr( event.srcElement ).val();
        }
        else
        {
            g.docType = $tigr( event.target ).val();
        }

        if( g.docType == 'document' )
        {
            g.showNewDocOpts();
        }
        else
        if( g.docType == 'spreadsheet' )
        {
            g.showNewSpreadOpts();
        }
    },

    resetDocList : function()
    {
        GoogleDocs.resetIndex();
        GoogleDocs.docList = GoogleDocs.docListOrig;
    },

    resetIndex : function()
    {
        GoogleDocs.startIndex = 0;
        GoogleDocs.endIndex   = GoogleDocs.DOCS_INCREMENT;
    },

    searchDocs : function( code )
    {
        var that = GoogleDocs;
        if( that.idleTimeout != null )
        {
            window.clearTimeout( that.idleTimeout );
            that.idleTimeout = null;
        }

        // Construct a new list based on the keyword.
        // ------------------------------------------
        // Do not trim keyword as document names can have spaces.
        // ------------------------------------------------------
        var keyword   = $tigr( '#gdocs_search' )[ 0 ].value;

        // We always reset the index back to the beginning.
        // ------------------------------------------------
        that.resetIndex();

        if( keyword.length == 0 )
        {
            that.resetDocList();
            that.refreshDocList();
        }
        else
        {
            // Backspace or Delete keys.
            // Cannot use Mozilla specific DOM_VK constants.
            // ---------------------------------------------
            var list    = ( code == 8 || code == 46 ) ? that.docListOrig : that.docList;
            var newList = [];

            $tigr.each
                (
                    list,
                    function( index, value )
                    {
                        var title = value.title.toLowerCase();
                        var key   = keyword.toLowerCase();

                        if( title.indexOf( key ) != -1 )
                        {
                            newList.push( value );
                        }
                    }
                );

            that.docList = newList;
            that.refreshDocList();
        }
    },

    onKeyUp : function( event )
    {
        var that = GoogleDocs;
        if( that.idleTimeout != null )
        {
            window.clearTimeout( that.idleTimeout );
            that.idleTimeout = null;
        }

        that.idleTimeout = window.setTimeout( function( code ) { that.searchDocs( code ); }, 500, event.keyCode );
    },

    getDocList : function(callback)
    {
        if( !this.docList )
        {
            this.docList    = [];
            this.startIndex = 0;
            this.endIndex   = this.DOCS_INCREMENT;

            // Get list of documents.
            // ----------------------
            var cid = Context.getClientID();
            $tigr.xget(
                {
                    url     : getYoProp('server')+'/yolink/googd?yact=ld&cid=' + cid + '&pid=' + cid + '&mode=lite',
                    success : function( data )
                    {

	 		var xml = typeof(data) == 'object' ? data.data : data;
                        if (!window.DOMParser)
                        {
                            xml       = new ActiveXObject('Microsoft.XMLDOM');
                            xml.async = false;
                            xml.loadXML(data);
                        }

                        if( xml )
                        {
                            $tigr( xml ).find( 'docEntry' ).each
                                (
                                    function()
                                    {
                                        var gdoc = new GoogleDocument( $tigr( this ).attr( 'starred' ),
                                                                       $tigr( this ).find( 'atitle' ).text(),
                                                                       $tigr( this ).find( 'resourceId' ).text(),
                                                                       $tigr( this ).find( 'modifiedDate' ).text(),
                                                                       $tigr( this ).find( 'sortModifiedDate' ).text(),
                                                                       $tigr( this ).find( 'docType' ).text(),
                                                                       $tigr( this ).find( 'folderName' ).text(),
                                                                       decodeURIComponent( $tigr( this ).find( 'iconUrl' ).text() ) );
                                        GoogleDocs.docList.push( gdoc );
                                    }
                                );
                        }

                        GoogleDocs.docListOrig = GoogleDocs.docList;

                        if( callback )
                        {
                            callback( GoogleDocs.docList );
                        }
                    }
                } );
        }
        else
        if( callback )
        {
            callback( GoogleDocs.docList );
        }
    },

    open : function()
    {
        GoogleDocs.getDocList(
            function( list )
            {
                $tigr( '#gdocs' ).dialog( 'option', 'chunktitle', Context.getDefaultTitle() );
                $tigr( '#gdocs' ).dialog( 'option', 'chunkurl', Context.getURL() );
                $tigr( '#gdocs' ).dialog( 'open' );
            } );
    },

    resetAllOpts : function()
    {
        $tigr( '#gdocs_createTableOption' ).attr( 'checked', false );
        $tigr( '#gdocs_appendCreateTableOption' ).attr( 'checked', false );
        $tigr( '#gdocs_appendAddTextToTopOption' ).attr( 'checked', false );

        // Default to saving in rows for spreadsheets.
        // -------------------------------------------
        $tigr( '#gdocs_saveInRowOption' ).attr( 'checked', true );
        $tigr( '#gdocs_appendSaveInRowOption' ).attr( 'checked', true );
    },

    showNewDocOpts : function()
    {
        GoogleDocs.hideNewSpreadOpts();
        $tigr( '#gdocs_createTableSpan' ).show();
    },

    hideNewDocOpts : function()
    {
        $tigr( '#gdocs_createTableSpan' ).hide();
    },

    showNewSpreadOpts : function()
    {
        GoogleDocs.hideNewDocOpts();
        $tigr( '#gdocs_saveInRowSpan' ).show();
    },

    hideNewSpreadOpts : function()
    {
        $tigr( '#gdocs_saveInRowSpan' ).hide();
    },

    showAppendDocOpts : function()
    {
        GoogleDocs.hideAppendSpreadOpts();
        $tigr( '#gdocs_appendCreateTableSpan' ).show();
        $tigr( '#gdocs_appendAddTextToTopSpan' ).show();
    },

    hideAppendDocOpts : function()
    {
        $tigr( '#gdocs_appendCreateTableSpan' ).hide();
        $tigr( '#gdocs_appendAddTextToTopSpan' ).hide();
    },

    showAppendSpreadOpts : function()
    {
        GoogleDocs.hideAppendDocOpts();
        $tigr( '#gdocs_appendSaveInRowSpan' ).show();
    },

    hideAppendSpreadOpts : function()
    {
        $tigr( '#gdocs_appendSaveInRowSpan' ).hide();
    },

    onOpen : function( event, ui )
    {
        GoogleDocs.resetAllOpts();

        // Hide all options by default.
        // ----------------------------
        GoogleDocs.hideNewDocOpts();
        GoogleDocs.hideNewSpreadOpts();
        GoogleDocs.hideAppendDocOpts();
        GoogleDocs.hideAppendSpreadOpts();

        // Set up for new document.
        // ------------------------
        $tigr( '#gdocs_actionNew' ).attr( 'checked', true );
        $tigr( '#gdocs_document' ).attr( 'checked', true );

        $tigr( '#gdocs_appendPanel' ).addClass( 'invisible' );
        $tigr( '#gdocs_newDocsPanel' ).removeClass( 'invisible' );

        GoogleDocs.action  = 'new';
        GoogleDocs.docType = 'document';

        GoogleDocs.showNewDocOpts();

        // Clear existing documents table.
        // -------------------------------
        //$tigr( '#gdocs_docListTblBody > tr' ).remove();

        // Clear all input boxes.
        // ----------------------
        $tigr( '#gdocs_docName' )[ 0 ].value = 'Untitled';
        $tigr( '#gdocs_search' )[ 0 ].value  = '';

        GoogleDocs.populateDocs();
    },

    refreshDocList : function()
    {
        GoogleDocs.togglePagination();
        GoogleDocs.updatePagination();
        GoogleDocs.populateDocs();
    },

    goNextPage : function( event )
    {
        GoogleDocs.selectedDoc = null;

        GoogleDocs.startIndex += GoogleDocs.DOCS_INCREMENT;
        GoogleDocs.endIndex   += GoogleDocs.DOCS_INCREMENT;

        var l = GoogleDocs.docList.length;
        if( GoogleDocs.endIndex > l )
        {
            GoogleDocs.endIndex = l;
        }

        GoogleDocs.refreshDocList();
    },

    goPrevPage : function( event )
    {
        GoogleDocs.selectedDoc = null;

        GoogleDocs.startIndex -= GoogleDocs.DOCS_INCREMENT;
        GoogleDocs.endIndex    = GoogleDocs.startIndex + GoogleDocs.DOCS_INCREMENT;

        GoogleDocs.refreshDocList();
    },

    togglePagination : function()
    {
        var l = this.docList.length;

        if( this.startIndex == 0 )
        {
            $tigr( '#gdocs_prev' ).addClass( 'invisible' );
        }
        else
        {
            $tigr( '#gdocs_prev' ).removeClass( 'invisible' );
        }

        if( this.endIndex >= l )
        {
            $tigr( '#gdocs_next' ).addClass( 'invisible' );
        }
        else
        {
            $tigr( '#gdocs_next' ).removeClass( 'invisible' );
        }
    },

    updatePagination : function()
    {
        var s = this.startIndex + 1;
        var e = ( this.docList.length < this.endIndex ) ? this.docList.length : this.endIndex;

        if( s > e )
        {
            s = e;
        }

        $tigr( '#gdocs_pagination' ).text( ( s + ' - ' + e + ' of ' + this.docList.length ) );
    },

    populateDocs : function()
    {
        // Clear the table first.
        // ----------------------
        $tigr( '#gdocs_docListTblBody > tr' ).remove();

        // Add the next set of documents.
        // ------------------------------
        var tbody = $tigr( '#gdocs_docListTblBody' );

        GoogleDocs.getDocList(
            function(list)
            {
                $tigr.each
                    (
                        list,
                        function( index, value )
                        {
                            if( index >= GoogleDocs.startIndex &&
                                index < GoogleDocs.endIndex )
                            {
                                tbody.append( $tigr( '<tr class="gdocs_row" idx="' + index              + '">'      +
                                                 '<td width="8%"><img src="'  + value.iconURL      + '"/></td>' +
                                                 '<td>'                       + value.title        + '</td>'   +
                                                 '<td width="48%">'           + value.modifiedDate + '</td>'   +
                                                 '</tr>' ) );
                            }
                        }
                    );

                // Apply alternating background.
                // -----------------------------
                $tigr( '#gdocs_docListTblBody > tr:odd' ).addClass( 'alt' );

                GoogleDocs.togglePagination();
                GoogleDocs.updatePagination();

                // Hide all options.
                // -----------------
                GoogleDocs.hideAppendDocOpts();
                GoogleDocs.hideAppendSpreadOpts();
            } )

    },

    onTableClick : function( event )
    {
        // Find the parent <TR> element.
        // -----------------------------
        var name = event.target.nodeName.toLowerCase();
        var tr   = null;

        if( name == 'td' )
        {
            tr = event.target.parentNode;
        }
        else
        if( name == 'img' )
        {
            tr = event.target.parentNode.parentNode;
        }

        if( tr != null )
        {
            // Extract the index and get the GoogleDocument object.
            // ----------------------------------------------------
            var that         = GoogleDocs;
            var idx          = tr.getAttribute( 'idx' );
            this.selectedDoc = this.docList[ idx ];

            // Highlight the selected row.
            // ---------------------------
            $tigr('.gdocs_row').removeClass('gdocs_hoverRow');
            $tigr('.gdocs_row > td').removeClass('gdocs_hoverRow_td');
            $tigr( tr ).addClass('gdocs_hoverRow');
            $tigr('td', tr).addClass('gdocs_hoverRow_td');

            // Show options for the selected document type.
            // --------------------------------------------
            if( that.selectedDoc.docType == 'document' )
            {
                that.showAppendDocOpts();
            }
            else
            if( that.selectedDoc.docType == 'spreadsheet' )
            {
                that.showAppendSpreadOpts();
            }
        }
    },

    onCancel : function( event )
    {
        GoogleDocs.docList     = null;
        GoogleDocs.docListOrig = null;

        $tigr( '#gdocs' ).dialog( 'close' );
    },

    onResult : function(result)
    {
        var type = typeof(result);
        var data = result;

        if( type == 'object' )
        {
            data = result.data;
        }
        else
        if( type == 'string' )
        {
            if (!window.DOMParser)
            {
                data       = new ActiveXObject('Microsoft.XMLDOM');
                data.async = false;
                data.loadXML(result);
            }
        }
        
        var url  = $tigr(data).find('url').text();
        // bug 3965 
        // Error 5001 is an gdoc authentication error. For some cases the googletoken is invalid so we need to handle
        // that error code by redirecting to the login screen again
        // -----------------------------------------------------------------------------
        var shouldRedirect =  $tigr(data).find('ErrorCause').text().indexOf('5001') !== -1;
        
        if( shouldRedirect )
        {
            url = $tigr(data).find('gloginurl').text();
        }

        url     = decodeURIComponent(url);
        tigr.util.Window.open(url);
    },

    sendCommand : function( action, options,  title, resourceId )
    {
        var cTitle  = $tigr( '#gdocs' ).dialog( 'option', 'chunktitle' );
        var cURL    = $tigr( '#gdocs' ).dialog( 'option', 'chunkurl' );
        var headers = {o          : 'text/plain',
                       yact       : action,
                       title      : title,
                       cid        : Context.getClientID(),
                       pid        : Context.getClientID(),
                       mode       : 'lite',
                       docTitle   : tigr.util.URLEncoder.encode(cTitle),
                       docUrl     : tigr.util.URLEncoder.encode(cURL),
                       ctable     : options.createTable,
                       rowlayout  : options.saveRow,
                       prepend    : options.addToTop,
                       productCode: 'weblabs'};
        if (resourceId)
        {
            headers.resid = resourceId;
        }

        $tigr.xpost(
                {
                    url        :getYoProp('server')+'/yolink/googdxml',
                    headers    :headers,
                    contentType:'text/plain',
                    success    :GoogleDocs.onResult,
                    data       :Context.getSelectedResults()});

        $tigr( '#gdocs' ).dialog( 'close' );
    },

    onOK : function( event )
    {
        var isValid = true;
        var url     = null;
        var dType   = '';
        var options =
        {
            createTable : '2',
            addToTop    : '0',
            saveRow     : '0'
        };

        if( GoogleDocs.action == 'new' )
        {
            var name = $tigr( '#gdocs_docName', GoogleDocs.doc )[ 0 ].value;
            if( name == null ||
                typeof( name ) == 'undefined' ||
                name.trim().length == 0 )
            {
                isValid = false;
            }

            if (GoogleDocs.docType == 'document')
            {
                dType = 'cd';
                if ($tigr('#gdocs_createTableOption', GoogleDocs.doc).is(':checked'))
                {
                    options.createTable = '1';
                }
            }
            else
            {
                dType = 'css';
                if ($tigr('#gdocs_saveInRowOption', GoogleDocs.doc).is(':checked'))
                {
                    options.saveRow = '1';
                }
            }

            if( isValid )
            {
                GoogleDocs.sendCommand( dType,
                                        options,
                                        $tigr( '#gdocs_docName', GoogleDocs.doc ).val(),
                                        null );
            }
        }
        else
        {
            if( GoogleDocs.selectedDoc == null ||
                typeof( GoogleDocs.selectedDoc ) == 'undefined' )
            {
                isValid = false;
            }

            if( isValid )
            {
                var d = GoogleDocs.selectedDoc;

                if (d.docType == 'document')
                {
                    dType = 'ud';

                    if ($tigr('#gdocs_appendCreateTableOption', GoogleDocs.doc).is(':checked'))
                        options.createTable = '1';

                    if ($tigr('#gdocs_appendAddTextToTopOption', GoogleDocs.doc).is(':checked'))
                        options.addToTop = '1';
                }
                else
                {
                    dType = 'uss';

                    if ($tigr('#gdocs_appendSaveInRowOption', GoogleDocs.doc).is(':checked'))
                        options.saveRow = '1';
                }

                GoogleDocs.sendCommand( dType,
                                        options,
                                        d.title,
                                        d.resourceId );
            }
        }
    },

    toggleNew : function( event )
    {
         //E3834:hide create table and save in a row related to append
        //-----------------------------------------------------------
        GoogleDocs.hideAppendDocOpts();
        GoogleDocs.hideAppendSpreadOpts();

        $tigr( '#gdocs_appendPanel' ).addClass( 'invisible' );
        $tigr( '#gdocs_newDocsPanel' ).removeClass( 'invisible' );

        GoogleDocs.action = 'new';
    },

    toggleAppend : function( event )
    {
        $tigr( '#gdocs_newDocsPanel' ).addClass( 'invisible' );
        $tigr( '#gdocs_appendPanel' ).removeClass( 'invisible' );

        GoogleDocs.action = 'add';
    },

    _isLoggedIn : undefined,
    _loginURL : '',

    isLoggedIn : function(callback)
    {
        if( GoogleDocs._isLoggedIn == undefined )
        {
            var cid = Context.getClientID();
            $tigr.xget(
                {
                    url     : getYoProp('server')+'/yolink/googd?yact=isloggedin&cid=' + cid + '&pid=' + cid + '&productCode=weblabs',
                    success : function(data)
                    {
                        var isError = false;
                        var text    = typeof(data) == 'object' ? data.data : data;
                        var xml     = text;

                        if (!window.DOMParser)
                        {
                            xml       = new ActiveXObject('Microsoft.XMLDOM');
                            xml.async = false;
                            xml.loadXML(text);
                        }

                        // Check for an error code.
                        // ------------------------
                        $tigr( xml ).find( 'errorCode' ).each
                            (
                                function()
                                {
                                    // OK, we got an error when checking to see if the user is logged in.
                                    // Reset the logged in status back to false.
                                    // ------------------------------------------------------------------
                                    GoogleDocs._isLoggedIn = true;
                                    isError                = true;
                                }
                            );

                        GoogleDocs._isLoggedIn = false;

                        if( !isError )
                        {
                            $tigr( xml ).find( 'data' ).each(
                                function(index,value)
                                {
                                    GoogleDocs._isLoggedIn = $tigr(value).text().trim() == "true";
                                }
                            );

                            $tigr( xml ).find( 'gloginurl' ).each(
                                function(index,value)
                                {
                                    GoogleDocs._loginURL   = decodeURIComponent( $tigr(value).text() );
                                    GoogleDocs._isLoggedIn = undefined;
                                }
                            );
                        }

                        if( callback )
                        {
                            callback( GoogleDocs._isLoggedIn );
                        }

                    }
                } );
        }
        else
        {
            if( callback )
            {
                callback( GoogleDocs._isLoggedIn );
            }
        }
    },

    getLoginURL : function()
    {
        return GoogleDocs._loginURL;
    }
};
/**
 *
 * Preview Window Drag Function to drag together the div tags preview_div_back ,  preview_div with included iframe
 *
 */

(function($tigr)
{

    // track if the mouse button is pressed
    //----------------------------------------
    var isMouseDown = false;
    var isMouseMoved = false;
    // track the current element being dragged
    //----------------------------------------
    var currentElement = null;

    // last mouse postions
    //----------------------
    var lastMouseX;
    var lastMouseY;
    //preview element last positions
    //-------------------------------
    var lastElemTop;
    var lastElemLeft;

    // track element drag status
    //----------------------------
    var dragStatus = {};

    //last window resize values
    //-------------------------
    var lastResizeWindowWidth;
    var lastResizeWindowHeight;
    /**
     *returns the mouse current position
     */
    $tigr.mousePositionOfCurrentMouseEvent = function(evnt)
    {
        var posx = 0;
        var posy = 0;

        if (!evnt) var e = window.event;

        if (evnt.pageX || evnt.pageY)
        {
            posx = evnt.pageX;
            posy = evnt.pageY;
        }
        else if (evnt.clientX || evnt.clientY)
        {
            posx = evnt.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
            posy = evnt.clientY + document.body.scrollTop + document.documentElement.scrollTop;
        }

        return { 'x': posx, 'y': posy };
    };

    /**
     *updates the position of the current #preview_div_back div and #preview_div and #preview_frame
     */
    $tigr.updatePreviewWindowPositionOnMouseMove = function(e)
    {
        var pos = $tigr.mousePositionOfCurrentMouseEvent(e);

        if (Preview.isResizeing)
        {
            var newWidth = Math.max(Preview.windowMinWidth, Preview.resizingWindowWidth + pos.x - lastMouseX);
            var newHeight = Math.max(Preview.windowMinHeight, Preview.resizingWindowHeight + pos.y - lastMouseY);

            Preview.setNewWinPositions(newWidth, newHeight);

            lastResizeWindowWidth = newWidth;
            lastResizeWindowHeight = newHeight;
        }
        else
        {

            var spanX = (pos.x - lastMouseX);
            var spanY = (pos.y - lastMouseY);

            var leftX = (lastElemLeft + spanX) ;
            var topY = (lastElemTop + spanY);

            var rightX = leftX + Preview.divWidth;
            var bottomY = topY + Preview.divHeight;
            var updateDivs = false;

            //leftx < leftX of window or rightx > rightX of window
            //topy < topX of Window or bottomY > bottomX of window
            //Check drag boundary
            //----------------------

            if ((rightX > (Preview.windowLeft + 50) ) && ( leftX < (Preview.windowLeft + Preview.windowWidth - 150)))   //left and right limits
            {
                updateDivs = true;
            }
            if ((updateDivs == true) && ( bottomY > 0 && ( bottomY > (Preview.windowTop + 70)))
                    && ( topY < (Preview.windowTop + Preview.windowHeight - 70))) //top and bottom limits
            {
                updateDivs = true;
            }
            else
            {

                updateDivs = false;

            }
            //allow drag only when within the window limits
            //----------------------------------------------
            if (updateDivs == true)
            {
                Preview.newdragTop = (lastElemTop + spanY);
                Preview.newdragLeft = (lastElemLeft + spanX);
                $tigr('#preview_div_back').css("top", (lastElemTop + spanY));
                $tigr('#preview_div_back').css("left", (lastElemLeft + spanX));
                if (tigr.util.IESupportsModernCSS(document))
                {
                    $tigr('#preview_div_back').css("position", 'fixed');
                    $tigr('#preview_div').css("position", 'fixed');
                }
                else
                {
                     $tigr('#preview_div_back').css("position", 'absolute');
                     $tigr('#preview_div').css("position", 'absolute');
                }

                
                $tigr('#preview_div').css("top", (lastElemTop + spanY));
                $tigr('#preview_div').css("left", (lastElemLeft + spanX));

                $tigr('#preview_frame_div').css("position", 'absolute');
                $tigr('#preview_frame_div').css("top", '30px');
                $tigr('#preview_frame_div').css("left", '8px');

                $tigr('#preview_frame').css("position", 'absolute');
            }
        }

    };
    /**
     *updates the position of the current #preview_div_back div and #preview_div and #preview_frame
     */
    $tigr.updatePreviewWindowPositionOnMouseUp = function(e)
    {
        var pos = $tigr.mousePositionOfCurrentMouseEvent(e);

        if (Preview.isResizeing)
        {
            var newWidth = Math.max(Preview.windowMinWidth, Preview.resizingWindowWidth + pos.x - lastMouseX);
            var newHeight = Math.max(Preview.windowMinHeight, Preview.resizingWindowHeight + pos.y - lastMouseY);

            Preview.setNewWinPositions(newWidth, newHeight);

            lastResizeWindowWidth = newWidth;
            lastResizeWindowHeight = newHeight;
        }
        else if(isMouseMoved == true)
        {

            var spanX = (pos.x - lastMouseX);
            var spanY = (pos.y - lastMouseY);

            var leftX = (lastElemLeft + spanX) ;
            var topY = (lastElemTop + spanY);

            var rightX = leftX + Preview.divWidth;
            var bottomY = topY + Preview.divHeight;
           
            //leftx < leftX of window or rightx > rightX of window
            //topy < topX of Window or bottomY > bottomX of window
            //Check drag boundary
            //----------------------

            var leftxBoundary = (Preview.windowLeft + Preview.windowWidth- 150);
            if(leftX  >=  leftxBoundary)
            {   
                leftX = leftxBoundary;
            }
            else if ( rightX <= (Preview.windowLeft + 50))
            {
                rightX = (Preview.windowLeft + 50);
                leftX =  rightX - Preview.divWidth;
            }
            
             var topyBoundary = (Preview.windowTop + Preview.windowHeight - 70);
           
            if(  bottomY <= (Preview.windowTop + 70)  )
            {
                bottomY = Preview.windowTop + 70;
                topY = bottomY - Preview.divHeight;
            }
            else if ( topY  >= topyBoundary)
            {
                topY = topyBoundary;
            }
            //allow drag only when within the window limits
            //----------------------------------------------
            Preview.newdragTop = topY;
            Preview.newdragLeft = leftX;
            $tigr('#preview_div_back').css("top", topY);
            $tigr('#preview_div_back').css("left", leftX);
            if (tigr.util.IESupportsModernCSS(document))
            {
                $tigr('#preview_div_back').css("position", 'fixed');
                $tigr('#preview_div').css("position", 'fixed');
            }
            else
            {
                 $tigr('#preview_div_back').css("position", 'absolute');
                 $tigr('#preview_div').css("position", 'absolute');
            }
            
            $tigr('#preview_div').css("top", topY);//(lastElemTop + spanY));
            $tigr('#preview_div').css("left", leftX);//(lastElemLeft + spanX));

            $tigr('#preview_frame_div').css("position", 'absolute');
            $tigr('#preview_frame_div').css("top", '30px');
            $tigr('#preview_frame_div').css("left", '8px');

            $tigr('#preview_frame').css("position", 'absolute');
            
        }

    };
    /**
     *when the mouse is moved while the mouse button is pressed
     */
    $tigr.mouseMoveOfCurrentMouseEvent = function(e)
    {
        if (isMouseDown && dragStatus[currentElement.id] == 'on')
        {
            isMouseMoved = true;
            if(Preview.optimizeDrag == false)
            {
                $tigr.updatePreviewWindowPositionOnMouseMove(e);
            }
            return false;
        }
    }
    /**
     *when the mouse button is released
     */
    $tigr.mouseUpOfCurrentMouseEvent = function(e)
    {
        if (isMouseDown && dragStatus[currentElement.id] == 'on')
        {
            if(Preview.optimizeDrag == true)
            {
                $tigr.updatePreviewWindowPositionOnMouseUp(e);
            }
            isMouseDown = false;
            isMouseMoved = false;
            Preview.isResizeing = false;
            if ($tigr('#overlay_iframe_fix') != null)
            {
                $tigr('#overlay_iframe_fix').remove();
                $tigr('#overlay_iframe_fix_body').remove();
            }
            if (lastResizeWindowWidth > 0)
            {
                Preview.resizingWindowWidth = lastResizeWindowWidth;
                Preview.resizingWindowHeight = lastResizeWindowHeight;
                Preview.divWidth = lastResizeWindowWidth;
                Preview.divHeight = lastResizeWindowHeight;
            }
            return isMouseDown;
        }
    }
    /**
     * bind mouse move call back on document
     */
    $tigr(document).mousemove(function(e)
    {
        return $tigr.mouseMoveOfCurrentMouseEvent(e);
    });

    /**
     * bind mouse move up back on document
     */
    $tigr(document).mouseup(function(e)
    {
        return $tigr.mouseUpOfCurrentMouseEvent(e);
    });


    /*
    *enable preview window drag
    */
    $tigr.fn.enablePreviewDrag = function()
    {

        return this.each(function()
        {

            // set dragStatus
            dragStatus[this.id] = "on";

            //handle mouse down event
            //----------------------
            $tigr(this).mousedown(function(e)
            {

                isMouseDown = true;
                currentElement = this;

                // retrieve mouse current positions
                //-----------------------------------
                var pos = $tigr.mousePositionOfCurrentMouseEvent(e);
                lastMouseX = pos.x;
                lastMouseY = pos.y;

                lastElemTop = this.offsetTop;
                lastElemLeft = this.offsetLeft;
                //update preview window position
                //------------------------------
                $tigr.updatePreviewWindowPosition(e);

                return  false;
            });

        });
    };

})($tigr);

/**
 * added to compare 2 arrays
 */
Array.prototype.startsWith = function (array)
{
    var matches = false;
    if (this.length >= array.length)
    {
        for (var i = 0; i < array.length; i++)
        {
            if (this[i] == array[i])
            {
                matches = true;
            }
            else
            {
                matches = false;
            }
        }
    }
    /*
    *	In case where the input array has more elements than the desired due to more tokens
    *	as the text nodes may be in different parents like "Wikipedia," which may be separated as 2 tokens
    *	where as the target source array may have it as one token
    */
    if (!matches)
    {
        var len = this.length;
        if (len > array.length)
        {
            len = array.length;
        }
        var thisstr = new tigr.util.StringBuffer();
        var arraystr = new tigr.util.StringBuffer();
        for (var i = 0; i < len; i++)
        {
            thisstr.append(this[i]);
            arraystr.append(array[i]);
        }
        var thisstrString = thisstr.toString().trim();
        var arraystrString = arraystr.toString().trim();
        if (thisstrString.length > 0 && arraystrString.length > 0)
        {
            if (thisstrString.startsWith(arraystrString))
            {
                matches = true;
            }

        }
    }

    return matches;
}

Array.prototype.stringIndexOf = function (array)
{
    var matches = false;
    var thisstr = new tigr.util.StringBuffer();
    var arraystr = new tigr.util.StringBuffer();
    for (var i = 0; i < this.length; i++)
    {
        thisstr.append(this[i]);

    }
    for (var i = 0; i < array.length; i++)
    {
        arraystr.append(array[i]);

    }

    var thisstrString = thisstr.toString().trim();
    var arraystrString = arraystr.toString().trim();
    if (thisstrString.length > 0 && arraystrString.length > 0)
    {
        if (thisstrString.indexOf(arraystrString) >= 0 || arraystrString.indexOf(thisstrString) >= 0)
        {
            matches = true;
        }

    }
    return matches;
}

Array.prototype.compareByWords = function (array, isEqual)
{
    var matchedCount = 0;
    var len = this.length;

    for (var i = 0; i < len && i < array.length; i++)
    {
        if (this[i] != array[i])
        {
            break;

        }

        matchedCount++;
    }

    if (isEqual)
    {
        return matchedCount == len;
    }

    var approximateMax = Math.floor(.5 * len);
    var matches = (matchedCount >= approximateMax) ;

    if (matches == false && matchedCount > 0)
    {
        if (len > array.length)
        {
            len = array.length;
        }
        var thisstr = new tigr.util.StringBuffer();
        var arraystr = new tigr.util.StringBuffer();
        matchedCount = 0;
        for (var i = 0; i < len; i++)
        {
            thisstr.append(this[i]);
            arraystr.append(array[i]);
            var thisstrStr = thisstr.toString();
            var arraystrStr = arraystr.toString();
            if (thisstrStr.startsWith(arraystrStr)
                    || arraystrStr.startsWith(thisstrStr)
                    || thisstrStr.indexOf(arraystrStr) >= 0
                    || arraystrStr.indexOf(thisstrStr) >= 0)
            {
                matchedCount += i;
            }

            if (matchedCount >= approximateMax)
            {
                matches = true;
                break;
            }

        }
    }

    return matches;

}

/**
 * finds all text nodes for all given chunk elements
 */
$tigr.fn.findMatchingTextNodesForAllElements = function(chunkElements)
{
    var chunkelementindex = 0;
    var foundTextNodes = [];
    var ret = [];
    //replace any new lines with space, <br>
    //---------------------------------------
    var textToFind = Pinning.trimNewLineBreaks($tigr(chunkElements[chunkelementindex]).text());
    //turn to upper case for case insensitive search
    //----------------------------------------------
    textToFind = textToFind.trim().toUpperCase();
    // split the chunk text to find into words
    //----------------------------------------
    var findtext = textToFind.split(" ");
    //array of chunk words to find
    //----------------------------
    var actualfinders = [];

    for (var i = 0; i < findtext.length; i++)
    {
        if (findtext[i].trim().length > 0)
        {
            // trim spaces of each word
            //-------------------------
            actualfinders.push(findtext[i].trim());

        }
    }

    //current scanning text words array
    //----------------------------------
    var documentTextArray = [];

    //current matched textnodes, will be discarded if no match
    //--------------------------------------------------------
    var currentRet = [];
    var previousChunkIndex = -1;
    //scann through the page preview frame document
    //---------------------------------------------
    this.contents().each(function()
    {
        try
        {
            var fn = arguments.callee;

            if (ret.length == 0)
            {

                //process text node
                //------------------
                if (this.nodeType == 3 && this.nodeType != 8 && !/(script|style|head)/i.test(this.tagName))
                {

                    //replace any new lines with space, <br>
                    //---------------------------------------
                    var thistext = Pinning.trimNewLineBreaks($tigr(this).text());
                    //turn to upper case for case insensitive search
                    //----------------------------------------------
                    thistext = thistext.trim().toUpperCase();
                    if (thistext.length > 0)
                    {
                        //if already matched, continue to match
                        //---------------------------------------
                        if (documentTextArray.length > 0 && thistext.length > 0)
                        {
                            var splittedText = thistext.split(" ");
                            //add this text node words to existing macthed ones
                            //-------------------------------------------------
                            for (var i = 0; i < splittedText.length; i++)
                            {
                                if (splittedText[i].trim().length > 0)
                                {
                                    documentTextArray.push(splittedText[i].trim());
                                }
                            }
                            if (actualfinders.equals(documentTextArray))//exact match
                            {
                                //add all matched text nodes
                                //--------------------------
                                if (currentRet.length > 0)
                                {
                                    for (var k = 0; k < currentRet.length; k++)
                                    {
                                        ret.push(currentRet[k]);
                                    }
                                }
                                ret.push(this);
                                //re-init
                                //--------
                                documentTextArray = [];
                                currentRet = []
                            }
                            //no match reset
                            //--------------
                            else
                            {
                                var matches = actualfinders.startsWith(documentTextArray);
                                if (!matches)
                                {
                                    currentRet = [];
                                    documentTextArray = [];
                                }
                                //approximate match
                                //------------------
                                else if (matches && actualfinders.length < documentTextArray.length)
                                {
                                    if (currentRet.length > 0)
                                    {
                                        for (var k = 0; k < currentRet.length; k++)
                                        {
                                            ret.push(currentRet[k]);
                                        }
                                    }
                                    ret.push(this);
                                    currentRet = []
                                    documentTextArray = [];
                                }
                                else if (matches)
                                {
                                    currentRet.push(this);
                                }
                                else if (actualfinders.length < documentTextArray.length)
                                {
                                    currentRet = [];
                                    documentTextArray = [];
                                }
                            }
                        }
                        //initial text node match
                        //-----------------------
                        else if (thistext.length > 0)
                        {
                            documentTextArray = [];
                            var splittedText = thistext.split(" ");
                            for (var i = 0; i < splittedText.length; i++)
                            {
                                if (splittedText[i].trim().length > 0 && documentTextArray.length <= actualfinders.length)
                                {
                                    documentTextArray.push(splittedText[i].trim());
                                }
                            }
                            //exact match
                            //---------------
                            if (actualfinders.equals(documentTextArray))
                            {
                                ret.push(this);
                                documentTextArray = [];

                            }
                            //starts with
                            //--------------
                            else if (actualfinders.startsWith(documentTextArray))
                            {
                                //save it and will be discarded if no match in next pass
                                //------------------------------------------------------
                                if (actualfinders.length < documentTextArray.length)
                                {
                                    ret.push(this);
                                    documentTextArray = [];
                                }
                                else
                                {
                                    currentRet.push(this);
                                }
                            }
                            else
                            {
                                documentTextArray = [];
                            }

                        }
                    }


                }
                else $tigr(this).contents().each(fn);

            }
            else    //found so go find next element
            {
                /*var thischunktextnodes = [];
                if (ret.length > 0)
                {
                    for (var i = 0; i < ret.length; i++)
                    {
                        thischunktextnodes.push(ret[i]);
                    }
                }*/
                if (ret.length > 0 && previousChunkIndex != chunkelementindex)
                {
                    foundTextNodes.push({cindex:chunkelementindex, nodes:ret});
                    previousChunkIndex = chunkelementindex;
                }
                chunkelementindex++;
                ret = [];
                textToFind = null;
                actualfinders = [];
                findtext = null;
                documentTextArray = [];
                currentRet = [];
                if (chunkelementindex < chunkElements.length)
                {

                    //replace any new lines with space, <br>
                    //---------------------------------------
                    textToFind = Pinning.trimNewLineBreaks($tigr(chunkElements[chunkelementindex]).text());
                    //turn to upper case for case insensitive search
                    //----------------------------------------------
                    textToFind = textToFind.trim().toUpperCase();
                    // split the chunk text to find into words
                    //----------------------------------------
                    findtext = textToFind.split(" ");
                    //array of chunk words to find
                    //----------------------------

                    for (var i = 0; i < findtext.length; i++)
                    {
                        if (findtext[i].trim().length > 0)
                        {
                            // trim spaces of each word
                            //-------------------------
                            actualfinders.push(findtext[i].trim());

                        }
                    }

                }

            }
        }
        catch (e)
        {
            // alert("findMatchingTextNodeParents " + e);
        }

    }
            );

    return foundTextNodes;
}


/*
*Scan through the text nodes of the preview frame page content to find the location
*of the chunk element hover text [textToFind]
*
*/
$tigr.fn.findMatchingTextNodeParents = function(textToFind)
{

    var ret = [];
    //replace any new lines with space, <br>
    //---------------------------------------
    textToFind = Pinning.trimNewLineBreaks(textToFind);
    //turn to upper case for case insensitive search
    //----------------------------------------------
    textToFind = textToFind.trim().toUpperCase();
    // split the chunk text to find into words
    //----------------------------------------
    var findtext = textToFind.split(" ");
    //array of chunk words to find
    //----------------------------
    var actualfinders = [];

    for (var i = 0; i < findtext.length; i++)
    {
        if (findtext[i].trim().length > 0)
        {
            // trim spaces of each word
            //-------------------------
            actualfinders.push(findtext[i].trim());

        }
    }

    //current scanning text words array
    //----------------------------------
    var documentTextArray = [];

    //current matched textnodes, will be discarded if no match
    //--------------------------------------------------------
    var currentRet = [];

    //scann through the page preview frame document
    //---------------------------------------------
    this.contents().each(function()
    {
        try
        {
            if (ret.length == 0)
            {
                var fn = arguments.callee;
                //process text node
                //------------------
                if (this.nodeType == 3 && this.nodeType != 8 && !/(script|style|head)/i.test(this.tagName))
                {

                    //replace any new lines with space, <br>
                    //---------------------------------------
                    var thistext = Pinning.trimNewLineBreaks($tigr(this).text());
                    //turn to upper case for case insensitive search
                    //----------------------------------------------
                    thistext = thistext.trim().toUpperCase();
                    if (thistext.length > 0)
                    {
                        //if already matched, continue to match
                        //---------------------------------------
                        if (documentTextArray.length > 0 && thistext.length > 0)
                        {
                            var splittedText = thistext.split(" ");
                            //add this text node words to existing macthed ones
                            //-------------------------------------------------
                            for (var i = 0; i < splittedText.length; i++)
                            {
                                if (splittedText[i].trim().length > 0)
                                {
                                    documentTextArray.push(splittedText[i].trim());
                                }
                            }
                            if (actualfinders.equals(documentTextArray))//exact match
                            {
                                //add all matched text nodes
                                //--------------------------
                                if (currentRet.length > 0)
                                {
                                    for (var k = 0; k < currentRet.length; k++)
                                    {
                                        ret.push(currentRet[k]);
                                    }
                                }
                                ret.push(this);
                                //ret.push($tigr(this).parent());
                                //re-init
                                //--------
                                documentTextArray = [];
                                currentRet = []
                            }
                            //no match reset
                            //--------------
                            else
                            {
                                var matches = actualfinders.startsWith(documentTextArray);
                                if (!matches)
                                {
                                    currentRet = [];
                                    documentTextArray = [];
                                }
                                //approximate match
                                //------------------
                                else if (matches && actualfinders.length < documentTextArray.length)
                                {
                                    if (currentRet.length > 0)
                                    {
                                        for (var k = 0; k < currentRet.length; k++)
                                        {
                                            ret.push(currentRet[k]);
                                        }
                                    }
                                    ret.push(this);
                                    currentRet = []
                                    documentTextArray = [];
                                }
                                else if (matches)
                                {
                                    currentRet.push(this);
                                }
                                else if (actualfinders.length < documentTextArray.length)
                                {
                                    currentRet = [];
                                    documentTextArray = [];
                                }
                            }
                        }
                        //initial text node match
                        //-----------------------
                        else if (thistext.length > 0)
                        {
                            documentTextArray = [];
                            var splittedText = thistext.split(" ");
                            for (var i = 0; i < splittedText.length; i++)
                            {
                                if (splittedText[i].trim().length > 0 && documentTextArray.length <= actualfinders.length)
                                {
                                    documentTextArray.push(splittedText[i].trim());
                                }
                            }
                            //exact match
                            //---------------
                            if (actualfinders.equals(documentTextArray))
                            {
                                ret.push(this);
                                documentTextArray = [];

                            }
                            //starts with
                            //--------------
                            else if (actualfinders.startsWith(documentTextArray))
                            {
                                //save it and will be discarded if no match in next pass
                                //------------------------------------------------------
                                if (actualfinders.length < documentTextArray.length)
                                {
                                    ret.push(this);
                                    documentTextArray = [];
                                }
                                else
                                {
                                    currentRet.push(this);
                                }
                            }
                            else
                            {
                                documentTextArray = [];
                            }

                        }
                    }


                }
                else $tigr(this).contents().each(fn);

            }
        }
        catch (e)
        {
            // alert("findMatchingTextNodeParents " + e);
        }

    }
            );

    return $tigr(ret);
}

$tigr(window).resize(
        function()
        {
            Preview.initWindowBoundaries();
        });
//----------------------------------
//Pinning script
//------------------------------------
Pinning =
{
    ENABLE_PINNING : true,
    textPreview    : false,
    currentPreviewURL  : null,
    currentPreviewResultIndex :-1,
    currentPageElementName : null,
    currentPageElementLocation : null,
    lastElementPinned : undefined,
    lastIdOfElementPinned : null,
    lastElementBorderCSSSet : false,
    lastHighLightedTextNode :[],
    lastInlineElementPinned : null,
    lastOnloadPinElement:null,
    highlightdiv : "<div id=\"tigr.pin.highlight\" class=\"yo_wrap_pinning_base yo_wrap_pinning\"  style=\"display:block\"/>",
    highlightselectiondiv:"<font class=\"yo_wrap_pinning_selection\" />",
    trimNewLineBreaks : function(text)
    {
        text = text.replace(/\n/g, " ");
        text = text.replace(/<br>/gi, " ");
        text = text.replace(/<br\/>/gi, " ");
        return text;
    },
    elementText : function(element)
    {
        var styledisplay = "display".toUpperCase();
        var none = "none".toUpperCase();

        var thisstr = new tigr.util.StringBuffer();
        $tigr(element).contents().each(
                function()
                {
                    var fn = arguments.callee;
                    //process text node
                    //------------------
                    if (this.nodeType == 3 && this.nodeType != 8)
                    {
                        var styleattr = $tigr(this).parent().attr("style");
                        var isDisplayNone = false;
                        if (styleattr != null && styleattr.toUpperCase().indexOf(styledisplay) >= 0)
                        {
                            if (styleattr.toUpperCase().indexOf(none) >= 0)
                            {
                                isDisplayNone = true;
                            }
                        }

                        if (!isDisplayNone)
                        {
                            thisstr.append($tigr(this).text());
                        }
                    }
                    else $tigr(this).contents().each(fn);
                }
                );
        return thisstr.toString();


    },
/**
 * compares the text() of element with actual text of the chunk
 * textToFind : actual chunk text
 * element : the element , the text of which needs to be compared with textToFind
 */
    elementTextMatches: function(textToFind, element, isEqual, evalDisplayNone)
    {
        var matches = false;
        var textToFindLength = textToFind.length;
        var textOfEachElement = (evalDisplayNone)?this.elementText(element).trim(): $tigr(element).text().trim();
        var thisTextLength = textOfEachElement.length ;
        if (thisTextLength > 0)
        {
            textOfEachElement = this.trimNewLineBreaks(textOfEachElement);
            textOfEachElement = textOfEachElement.trim().toUpperCase();
            //check if text with no space matches
            //-------------------------------------
            var textOfEachElementNoSpaces = textOfEachElement.replace(/ /gi, "");
            var textToFindNoSpaces = textToFind.replace(/ /gi, "");
            if (isEqual)
            {
                matches = (textOfEachElementNoSpaces == textToFindNoSpaces);

            }
            else
            {
                var approximate = Math.floor(textToFindNoSpaces.length * 0.5);

                if (textOfEachElementNoSpaces.length >= approximate)
                {

                    matches = ( textOfEachElementNoSpaces.indexOf(textToFindNoSpaces) >= 0
                            || textToFindNoSpaces.indexOf(textOfEachElementNoSpaces) >= 0
                            || textOfEachElementNoSpaces.startsWith(textToFindNoSpaces)
                            || textToFindNoSpaces.startsWith(textOfEachElementNoSpaces) );
                }

            }

            if (!matches)  //check with words
            {
                var max = Math.floor(textToFindNoSpaces.length * 1.5);
                if (textOfEachElementNoSpaces.length <= max)
                {
                    // split the chunk text to find into words
                    //----------------------------------------
                    var findtext = textToFind.split(" ");
                    //array of chunk words to find
                    //----------------------------
                    var actualFinders = [];

                    for (var i = 0; i < findtext.length; i++)
                    {
                        if (findtext[i].trim().length > 0)
                        {
                            // trim spaces of each word
                            //-------------------------
                            actualFinders.push(findtext[i].trim());

                        }
                    }
                    var textFindersOfEachElement = [];
                    var eachtextArray = textOfEachElement.split(" ");
                    for (var j = 0; j < eachtextArray.length; j++)
                    {
                        if (eachtextArray[j].trim().length > 0)
                        {
                            // trim spaces of each word
                            //-------------------------
                            textFindersOfEachElement.push(eachtextArray[j].trim());

                        }
                    }

                    var targetElementWords = textFindersOfEachElement.length;
                    var sourceChunkWords = actualFinders.length;
                    max = Math.floor(sourceChunkWords * (1.3));
                    if (targetElementWords <= max) //ignore large parent elements that includes more text
                    {

                        if (isEqual)
                        {
                            matches = actualFinders.compareByWords(textFindersOfEachElement, true);
                            //exact match

                        }
                        else //approximate match
                        {
                            matches = actualFinders.compareByWords(textFindersOfEachElement, false);

                        }
                    }//array max

                }//if str no space max

            }//if no match
        }
        return matches;

    },

/**
 * find element name, location, virtual info for each element and group by element name
 */
    findAllNamesAndLocations :function (chunkelems)
    {
        var uniqueElemNames = [];
        for (var i = 0; i < chunkelems.length; i++)
        {
            var nameLocation = null;
            //chunk type either virtual true/false
            //--------------------------------------
            var virtual = null;

            nameLocation = $tigr(chunkelems[i]).attr("namelocation");
            virtual = $tigr(chunkelems[i]).attr("virtual");
            //call pin on the page content preview window
            //---------------------------------------------
            var actualName = null;
            var elemlocation = null;


            if (nameLocation != null)
            {
                var name = nameLocation.split("_");
                var name1 = name[0].split("}");

                if (name1 != null && name1.length > 0)
                {
                    actualName = name1[1];
                }
                else
                {
                    actualName = name[0];
                }

                if (name != null && name.length > 1 && name[1].trim().length > 0)
                {
                    elemlocation = name[1];
                }
            }

            var nameindex = -1;
            for (var k = 0; k < uniqueElemNames.length; k++)
            {
                if (uniqueElemNames[k].name == actualName)
                {
                    nameindex = k;
                    break;
                }
            }

            if (nameindex >= 0)
            {
                uniqueElemNames[nameindex].locations.push({elem:chunkelems[i],elemlocation:elemlocation,isvirtual:virtual})
            }
            else
            {
                var loc = new Array();
                loc.push({elem:chunkelems[i],elemlocation:elemlocation,isvirtual:virtual});
                uniqueElemNames.push({name:actualName, locations: loc });
            }

        }
        return uniqueElemNames;

    },
/**
 * static pin all preview elements on the given document .
 */
    pinAllPreviewPageElementsByNameAndText : function(chunkelems, documentElem)
    {
        try
        {
            var uniqueElemNames = this.findAllNamesAndLocations(chunkelems);
            var findTextNodesForElements = [];
            for (var ue = 0; ue < uniqueElemNames.length; ue++)
            {
                var elemName = uniqueElemNames[ue].name;
                var locations = uniqueElemNames[ue].locations;
                var elements = documentElem.body.getElementsByTagName(elemName);
                //pin all elements with a specified location 
                //-------------------------------------------
                if (locations != null && locations.length > 0)
                {
                    for (var locindex = 0; locindex < locations.length; locindex++)
                    {
                        var isVirtual = locations[locindex].isvirtual;
                        var textToFind = $(locations[locindex].elem).text();
                        var textToFindLength = textToFind.length;
                        textToFind = this.trimNewLineBreaks(textToFind);
                        textToFind = textToFind.trim().toUpperCase();

                        var index = (locations[locindex].elemlocation) - 1;
                        var mostrelevant = null;

                        var elem = null;
                        if (index >= 0)
                        {
                            elem = elements[index];
                        }
                        if (elem != null && this.elementTextMatches(textToFind, elem, true, true))
                        {
                            mostrelevant = elem;
                        }
                        else
                        {
                            //first try after the given location
                            var start = index + 1;
                            if (start < elements.length)
                            {
                                var end = elements.length;
                                var percentLimit = start + Math.floor((elements.length - start) * 0.60);
                                if (percentLimit < elements.length)
                                {
                                    end = percentLimit;
                                }
                                mostrelevant = this.findMatchingElementFromStart(start, end, textToFind, elements, true);

                            }
                            if (mostrelevant == null)
                            {
                                var start = index - 1;
                                var end = 0;
                                if (start >= 0)
                                {
                                    var percentLimit = start - Math.floor((start - end) * 0.50);
                                    if (percentLimit > end)
                                    {
                                        end = percentLimit;
                                    }

                                    //try before the given location
                                    mostrelevant = this.findMatchingElementFromEnd(start, end, textToFind, elements, true);

                                }

                            }
                        }
                        if (mostrelevant != null)
                        {
                            //find if any child elements match to
                            //exactly pin the correct elements
                            //------------------------------------
                            var foundMatchingChild = null;
                            $tigr(mostrelevant)
                                    .contents()
                                    .filter(function()
                            {
                                if (foundMatchingChild == null)
                                {
                                    if (isVirtual && this.nodeType == 3) //Node.TEXT_NODE;
                                    {
                                        if (Pinning.elementTextMatches(textToFind, this, true, false))
                                        {
                                            foundMatchingChild = this;
                                        }

                                    }
                                    else
                                    {
                                        if (Pinning.elementTextMatches(textToFind, this, true, false))
                                        {
                                            foundMatchingChild = this;
                                        }

                                    }
                                }
                            });
                            if (foundMatchingChild != null)
                            {
                                mostrelevant = foundMatchingChild;
                            }

                        }
                        //no exact match so try for approximate match
                        //--------------------------------------------
                        if (mostrelevant == null)
                        {
                            //first try after the given location
                            var start = index ;
                            if (start < 0)
                            {
                                start = 0;
                            }
                            if (start < elements.length)
                            {
                                var end = elements.length;
                                mostrelevant = this.findMatchingElementFromStart(start, end, textToFind, elements, false);
                            }
                            if (mostrelevant == null)
                            {
                                var start = index - 1;
                                var end = 0;
                                if (start >= 0)
                                {
                                    //try before the given location
                                    mostrelevant = this.findMatchingElementFromEnd(start, end, textToFind, elements, false);
                                }
                            }

                            if (mostrelevant != null)
                            {
                                //find if any child elements match to
                                //exactly pin the correct elements
                                //------------------------------------
                                var foundMatchingChild = null;
                                //var total =0;
                                $tigr(mostrelevant)
                                        .contents()
                                        .filter(function()
                                {
                                    if (foundMatchingChild == null)
                                    {
                                        if (isVirtual && this.nodeType == 3) //only Node.TEXT_NODE;
                                        {
                                            if (Pinning.elementTextMatches(textToFind, this, false, false))
                                            {
                                                foundMatchingChild = this;
                                            }

                                        }
                                        else
                                        {
                                            if (Pinning.elementTextMatches(textToFind, this, false, false))
                                            {
                                                foundMatchingChild = this;
                                            }

                                        }
                                    }
                                });

                                if (foundMatchingChild != null)
                                {
                                    mostrelevant = foundMatchingChild;
                                }

                            }


                        }

                        if (mostrelevant != null && mostrelevant.nodeType != 3 &&
                            (isVirtual == true || $(mostrelevant).text().trim().length > textToFindLength ))

                        {
                            var alltextNodes = $tigr(mostrelevant).findMatchingTextNodeParents(textToFind);
                            if (alltextNodes != null && alltextNodes.length > 0)
                            {

                                for (var k = 0; k < alltextNodes.length; k++)
                                {
                                    $tigr(alltextNodes[k]).wrap(Pinning.highlightselectiondiv);
                                }

                            }
                            else
                            {
                                this.pinningBoxCSS(mostrelevant, true);
                            }
                        }
                        else if (mostrelevant != null)
                        {
                            this.pinningBoxCSS(mostrelevant, true);
                        }


                        if (mostrelevant == null)
                        {
                            findTextNodesForElements.push(locations[locindex].elem);
                        }
                        mostrelevant = null;
                        isVirtual = undefined;
                        textToFind = "";
                        index = -1;

                    }
                    //inner location for loop

                } //location if

                elements = null;
            }
            //main for loop

            //if the elements are virtual and no location info , find text nodes and pin them
            //----------------------------------------------------------------------------------
            if (findTextNodesForElements.length > 0)
            {
                this.pinAllElementsHighLightText(findTextNodesForElements);
            }


        }
        catch (e)
        {
            // alert("findAllPreviewPageElementByNameAndText " + e);
        }


    },

/**
 *  pins with high lighting the text nodes for the given chunk elements
 */
    pinAllElementsHighLightText : function(chunkElements)
    {
        try
        {
            var notFoundElements = [];
            //scan through the preview frame  document and
            //find the parents of textnodes to high light the selection
            //----------------------------------------------------------
            var fname = $tigr.browser.iPad == true ? '#yopadpreview_frame' : '#preview_frame';
            var textnodes = $tigr(fname).findMatchingTextNodesForAllElements(chunkElements);

            if (textnodes.length > 0)
            {
                for (var i = 0; i < textnodes.length; i++)
                {
                    if (textnodes[i].nodes != null && textnodes[i].nodes.length > 0)
                    {
                        for (var k = 0; k < textnodes[i].nodes.length; k++)
                        {
                            $tigr(textnodes[i].nodes[k]).wrap(Pinning.highlightselectiondiv);
                        }
                    }
                    else
                    {
                        notFoundElements.push(chunkElements[textnodes[i].cindex]);
                    }
                }
            }

            if (notFoundElements.length > 0)
            {
                var textnodes = $tigr(fname).findMatchingTextNodesForAllElements(chunkElements);
                if (textnodes.length > 0)
                {
                    for (var i = 0; i < textnodes.length; i++)
                    {
                        if (textnodes[i].nodes != null && textnodes[i].nodes.length > 0)
                        {
                            for (var k = 0; k < textnodes[i].nodes.length; k++)
                            {
                                $tigr(textnodes[i].nodes[k]).wrap(Pinning.highlightselectiondiv);
                            }
                        }
                        else
                        {
                            notFoundElements.push(chunkElements[textnodes[i].cindex]);
                        }
                    }
                }
            }


            if (notFoundElements.length > 0)
            {
                var prevWin = Preview.findPreviewWindow();
                var prevDoc = Preview.findPreviewDoc();
                for (var i = 0; i < notFoundElements.length; i++)
                {
                    this.pinByText($tigr(notFoundElements[i]).text(), prevWin, prevDoc, false);
                }
            }


        }
        catch (e)
        {
            //alert("pinAllHighLightElementText " + e);
        }
    },


/**
 * find preview page element for pinning based on chunk text on mouse hover and element name
 * since exact loaction is not known search on element name and with matched text
 */
    findPreviewPageElementByNameAndText : function(textToFind, elementName, elementLocation, documentElem, isVirtual)
    {
        var mostrelevant = null;
        try
        {
            var textToFindLength = textToFind.length;
            textToFind = this.trimNewLineBreaks(textToFind);
            textToFind = textToFind.trim().toUpperCase();
            // split the chunk text to find into words
            if (documentElem.body != null)
            {
                var elements = documentElem.body.getElementsByTagName(elementName);
                var index = elementLocation - 1;
                if (elementLocation != null && elements.length > 0)
                {

                    var elem = null;

                    if (index >= 0)
                    {
                        elem = elements[index];
                    }
                    if (elem != null && this.elementTextMatches(textToFind, elem, true, true))
                    {
                        mostrelevant = elem;
                    }
                    else
                    {
                        //first try after the given location
                        var start = index + 1;
                        if (start < elements.length)
                        {
                            var end = elements.length;
                            var percentLimit = start + Math.floor((elements.length - start) * 0.60);
                            if (percentLimit < elements.length)
                            {
                                end = percentLimit;
                            }
                            mostrelevant = this.findMatchingElementFromStart(start, end, textToFind, elements, true);

                        }
                        if (mostrelevant == null)
                        {
                            var start = index - 1;
                            var end = 0;
                            if (start >= 0)
                            {
                                var percentLimit = start - Math.floor((start - end) * 0.50);
                                if (percentLimit > end)
                                {
                                    end = percentLimit;
                                }

                                //try before the given location
                                mostrelevant = this.findMatchingElementFromEnd(start, end, textToFind, elements, true);

                            }

                        }

                    }
                    if (mostrelevant != null)
                    {
                        //find if any child elements match to
                        //exactly pin the correct elements
                        //------------------------------------
                        var foundMatchingChild;
                        $tigr(mostrelevant)
                                .contents()
                                .filter(function()
                        {

                            if (foundMatchingChild == null)
                            {
                                if (isVirtual && this.nodeType == 3) //Node.TEXT_NODE;
                                {
                                    if (Pinning.elementTextMatches(textToFind, this, true, false))
                                    {
                                        foundMatchingChild = this;
                                    }

                                }
                                else
                                {
                                    if (Pinning.elementTextMatches(textToFind, this, true, false))
                                    {
                                        foundMatchingChild = this;
                                    }

                                }
                            }
                        });
                        if (foundMatchingChild != null)
                        {
                            mostrelevant = foundMatchingChild;
                        }

                    }

                }

                //no exact match so try for approximate match
                //--------------------------------------------
                if (mostrelevant == null)
                {
                    //first try after the given location
                    var start = index ;
                    if (start < 0)
                    {
                        start = 0;
                    }
                    if (start < elements.length)
                    {
                        var end = elements.length;
                        mostrelevant = this.findMatchingElementFromStart(start, end, textToFind, elements, false);
                    }
                    if (mostrelevant == null)
                    {
                        var start = index - 1;
                        var end = 0;
                        if (start >= 0)
                        {
                            //try before the given location
                            mostrelevant = this.findMatchingElementFromEnd(start, end, textToFind, elements, false);
                        }
                    }

                    if (mostrelevant != null)
                    {
                        //find if any child elements match to
                        //exactly pin the correct elements
                        //------------------------------------
                        var foundMatchingChild;
                        //var total =0;
                        $tigr(mostrelevant)
                                .contents()
                                .filter(function()
                        {
                            if (foundMatchingChild == null)
                            {
                                if (isVirtual && this.nodeType == 3) //only Node.TEXT_NODE;
                                {
                                    //total++;
                                    //("index --2--"+$tigr(this).text());
                                    if (Pinning.elementTextMatches(textToFind, this, false, false))
                                    {
                                        foundMatchingChild = this;
                                    }

                                }
                                else
                                {
                                    if (Pinning.elementTextMatches(textToFind, this, false, false))
                                    {
                                        foundMatchingChild = this;
                                    }

                                }
                            }
                        });

                        if (foundMatchingChild != null)
                        {
                            mostrelevant = foundMatchingChild;
                        }

                    }


                }

            }//document.body != null
        }
        catch (e)
        {
            //alert("findPreviewPageElementByNameAndText "+e);
        }

        var alltextNodes = null;
        try
        {
            if (mostrelevant != null && mostrelevant.nodeType != 3 &&
                (isVirtual == true || $(mostrelevant).text().trim().length > textToFindLength ))

            {
                alltextNodes = $tigr(mostrelevant).findMatchingTextNodeParents(textToFind);
            }
        }
        catch (e)
        {
            //alert("findPreviewPageElementByNameAndText "+e);
        }
        return ((alltextNodes != null && alltextNodes.length > 0)? { elems:alltextNodes,textnodes:true} :{ elems:mostrelevant,textnodes:false} );

    },


    findMatchingElementFromStart : function(start, end, textToFind, elemntsArray, isEqual)
    {
        var matchedElement = null;
        for (var i = start; i < end; i++)
        {
            if (this.elementTextMatches(textToFind, elemntsArray[i], isEqual, true))
            {
                matchedElement = elemntsArray[i];
                break;
            }

        }
        return matchedElement;
    },
    findMatchingElementFromEnd : function(start, end, textToFind, elemntsArray, isEqual)
    {
        var matchedElement = null;
        for (var i = start; i >= end; i--)
        {
            if (this.elementTextMatches(textToFind, elemntsArray[i], isEqual, true))
            {
                matchedElement = elemntsArray[i];
                break;
            }

        }
        return matchedElement;
    },

/**
 *	find preview page element for pinning based on chunk text on mouse hover , element name and  location
 */
    findPreviewPageElement: function(name, elemlocation, text, isVirtual)
    {
        var docElm = Preview.findPreviewDoc();
        if (docElm == null)
        {
            return null;
        }
        else
        {
            return this.findPreviewPageElementByNameAndText(text, name, elemlocation, docElm, isVirtual);
        }
    },
/**
 * high lights the selected text on the preview page in case if exact location  to pin is failed.
 * This is a fall back in case all options to find the location on preview page.
 */
    pinHighLightElementText : function(over, textToFind)
    {
        try
        {
            //scan through the preview frame  document and
            //find the parents of textnodes to high light the selection
            //----------------------------------------------------------
            var oneTextNodeParent = null;
            if (over)
            {
                var fname = $tigr.browser.iPad == true ? '#yframe' : '#preview_frame';
                var textnodes = $tigr(fname).findMatchingTextNodeParents(textToFind);
                if (textnodes.length > 0)
                {
                    this.pinTextNodes(textnodes);
                }
                else
                {
                    this.pinByText(textToFind, Preview.findPreviewWindow(), Preview.findPreviewDoc(), true);
                }
            }
        }
        catch (e)
        {
            //alert("pinHighLightElementText "+e);
        }
    },

    pinTextNodes: function(textnodes)
    {
        try
        {
            
        var oneTextNodeParent = null;
        for (var i = 0; i < textnodes.length; i++)
        {
            $tigr(textnodes[i]).wrap(Pinning.highlightselectiondiv);
            Pinning.lastHighLightedTextNode.push(textnodes[i]);
        }
        oneTextNodeParent = $tigr(textnodes[0]).parent().get(0);
        if ($tigr.browser.msie)
        {
             if(tigr.util.IESupportsModernCSS(document))
             {
                $tigr(oneTextNodeParent).scrollIntoView(true);
             }
             else
             {
                var docElm = Preview.findPreviewDoc();
                var body = docElm.getElementsByTagName('body')[ 0 ];
                $tigr(body).animate({scrollTop:  tigr.util.elemY(oneTextNodeParent) - 10, scrollLeft:  tigr.util.elemX(oneTextNodeParent) - 10}, 500);
             }


        }
        else if ($tigr.browser.mozilla)
        {
            var parentelem = oneTextNodeParent;
            if (parentelem.nodeName.toUpperCase() == "BODY")
            {
                var docElm = Preview.findPreviewDoc();
                var body = docElm.getElementsByTagName('body')[ 0 ];
                $tigr(body).animate({scrollTop:  tigr.util.elemY(oneTextNodeParent) , scrollLeft:  tigr.util.elemX(oneTextNodeParent) }, 500);
            }
            else
            {
                parentelem.scrollIntoView(true);
            }
        }
        else
        {
            var docElm = Preview.findPreviewDoc();
            var body = docElm.getElementsByTagName('body')[ 0 ];
            $tigr(body).animate({scrollTop:  tigr.util.elemY(oneTextNodeParent) - 10, scrollLeft:  tigr.util.elemX(oneTextNodeParent) - 10}, 500);
        }

         }
        catch (e)
        {
            //alert("pinTextNodes :"+e);
        }
    }   ,

/**
 * pins the given chunk element with box css style
 */
    pinningBoxCSS: function(elem, over)
    {
        var floatcss = null;
        var name = elem.nodeName.toUpperCase();
        if (elem.nodeType != 3)
        {
            floatcss = $tigr(elem).css("float");
        }
        if (floatcss != null)
        {
            floatcss = floatcss.toUpperCase();
        }
        if (over)
        {
            if (name == 'OL' || name == 'LI' || name == 'UL' || name == 'P'
                    || name == 'TD' || name == 'TR')
            {
                this.lastIdOfElementPinned = $tigr(elem).attr("id");
                $tigr(elem).attr("id", "yo_pin_elemid");
                var borderinlinestyle = $tigr(elem).css("border");
                if (borderinlinestyle != null && borderinlinestyle.indexOf("none") >= 0)
                {
                    $tigr(elem).css("border-style", "solid");
                    $tigr(elem).css("border-width", "1px 4px 4px 1px");
                }
                var textindent = $tigr(elem).css("text-indent");
                if (textindent != null && ( textindent.toLowerCase() != "0px" || textindent.toLowerCase() != "0pt"))
                {
                    $tigr(elem).css("text-indent", "0px");
                }
                //override if it is inline
                $tigr(elem).css("display", "block");
            }
            //for floating elements addclass
            //---------------------------------
            else if (floatcss != null && floatcss != "NONE")
            {
                $tigr(elem).addClass("yo_wrap_pinning_base yo_wrap_pinning ");
                var borderinlinestyle = $tigr(elem).css("border");
                if (borderinlinestyle != null && borderinlinestyle.indexOf("none") >= 0)
                {
                    $tigr(elem).css("border-style", "solid");
                    $tigr(elem).css("border-width", "1px 4px 4px 1px");
                    this.lastElementBorderCSSSet = true;
                }
                var textindent = $tigr(elem).css("text-indent");
                if (textindent != null && ( textindent.toLowerCase() != "0px" || textindent.toLowerCase() != "0pt"))
                {
                    $tigr(elem).css("text-indent", "0px");
                }
                //override if it is inline
                $tigr(elem).css("display", "block");
            }
            else
            {
                $tigr(elem).wrap(Pinning.highlightdiv);


            }
        }
        else
        {
            if (name == 'OL' || name == 'LI' || name == 'UL'
                    || name == 'P' || name == 'TD' || name == 'TR')
            {
                if (this.lastIdOfElementPinned != null)
                {
                    $tigr(elem).attr("id", this.lastIdOfElementPinned);
                }
                else
                {
                    $tigr(elem).removeAttr("id");
                }
                this.lastIdOfElementPinned = null;

            }
            else if (floatcss != null && floatcss != "NONE")
            {
                $tigr(elem).removeClass("yo_wrap_pinning_base yo_wrap_pinning ");
                if (this.lastElementBorderCSSSet)
                {
                    $tigr(elem).css("border", "none");
                }
                this.lastElementBorderCSSSet = false;
            }
            else
            {
                $tigr(elem).unwrap();
            }
        }

    }  ,
/**
 * pinning the selected element (elem) on the preview page document
 *
 */
    pin : function(elem, active)
    {
        try
        {

            var docElm = Preview.findPreviewDoc();
            var body = docElm.getElementsByTagName('body')[ 0 ];
            var name = elem.nodeName.toUpperCase();

            this.pinningBoxCSS(elem, active);
            if (active)
            {
                //add css pin id for the following to prevent alignment issue
                //-------------------------------------------------------------

                this.lastElementPinned = elem;

                if (elem.nodeType == 3)
                {
                    elem = $tigr(elem).parent().get(0)
                }

                if ($tigr.browser.mozilla  )
                {

                    elem.scrollIntoView(true);
                }
                else if ($tigr.browser.msie)
                {
                    if(tigr.util.IESupportsModernCSS(document))
                    {
                        elem.scrollIntoView(true);
                    }
                    else
                    {
                        var x = tigr.util.elemX(elem);
                        var y = tigr.util.elemY(elem);
                        $tigr(body).animate({scrollTop:  y - 10, scrollLeft:   x - 10}, 500);
                    }
                }
                else
                {
                    var x = tigr.util.elemX(elem);
                    var y = tigr.util.elemY(elem);

                    $tigr(body).animate({scrollTop:  y - 10, scrollLeft:   x - 10}, 500);
                }

            }
            else
            {

                this.lastElementPinned = null;
            }

        }
        catch (e)
        {
            //  alert("pin :"+e);
        }
    },
    inlinepin : function(active)
    {
        try
        {

            if (this.lastInlineElementPinned != null)
            {

                if (active)
                {

                    if (this.lastInlineElementPinned.textnodes == true)
                    {
                        for (var i = 0; i < this.lastInlineElementPinned.elems.length; i++)
                        {
                            $tigr(this.lastInlineElementPinned.elems[i]).wrap(Pinning.highlightselectiondiv);
                        }

                    }
                    else
                    {

                        $tigr(this.lastInlineElementPinned.elems).wrap(Pinning.highlightdiv);
                        var elem = this.lastInlineElementPinned.elems;
                        if (this.lastInlineElementPinned.elems.nodeType == 3)
                        {
                            elem = $tigr(elem).parent().get(0)
                        }

                        if ($tigr.browser.mozilla )
                        {
                            elem.scrollIntoView(true);
                        }
                        else if ($tigr.browser.msie)
                        {
                                if(tigr.util.IESupportsModernCSS(document))
                                {
                                    elem.scrollIntoView(true);
                                }
                                else
                                {
                                    var x = tigr.util.elemX(elem);
                                    var y = tigr.util.elemY(elem);
                                    var body = document.getElementsByTagName('body')[ 0 ];

                                    $tigr(body).animate({scrollTop:  y - 10, scrollLeft:   x - 10}, 500);
                                }
                           
                        }
                        else
                        {
                            var x = tigr.util.elemX(elem);
                            var y = tigr.util.elemY(elem);
                            var body = document.getElementsByTagName('body')[ 0 ];

                            $tigr(body).animate({scrollTop:  y - 10, scrollLeft:   x - 10}, 500);
                        }
                    }


                }
                else
                {

                    if (this.lastInlineElementPinned.textnodes == true)
                    {
                        for (var i = 0; i < this.lastInlineElementPinned.elems.length; i++)
                        {
                            $tigr(this.lastInlineElementPinned.elems[i]).unwrap();

                        }

                    }
                    else if (this.lastInlineElementPinned.elems != null)
                    {
                        $tigr(this.lastInlineElementPinned.elems).unwrap();

                    }
                    else
                    {
                        try
                        {
                            var sel = window.getSelection();
                            if (sel.rangeCount > 0)
                            {
                                sel.removeAllRanges();
                            }
                        }
                        catch(e)
                        {
                        }
                    }

                    this.lastInlineElementPinned = null;
                }
            }

        }
        catch (e)
        {
            //alert("pin :"+e);
        }
    },

    clearPin: function()
    {
        if ($tigr.browser.iPad == true)
        {
            return;
        }
        if (this.lastElementPinned != null)
        {
            this.pin(this.lastElementPinned, false);
            this.lastElementPinned = null;
        }
        else if (this.lastHighLightedTextNode.length > 0)
        {
            for (var i = 0; i < this.lastHighLightedTextNode.length; i++)
            {
                $tigr(this.lastHighLightedTextNode[i]).unwrap();

            }
            this.lastHighLightedTextNode = [];
        }
        else
        {
            var previewContent = Preview.findPreviewWindow();
            try
            {
                var sel = previewContent.getSelection();
                if (sel.rangeCount > 0)
                {
                    sel.removeAllRanges();
                }
            }
            catch(e)
            {
            }
        }

    },
/**
 * finds pinning element location  using "/yolinklite/find" for chunks which are NOT virtual but unable to
 * find the element by the id attribute of each <r> element
 * sends the full page content of preview page DOM document to match the exact location
 */
    findPreviewPageElementLocationService: function(url, text, pageContent, over)
    {
        if (over)
        {
            var encodetext = text.trim().replace(/ /g, "+");
            setTimeout(function()
            {
                $tigr.xget({url: getYoProp('server') + '/yolinklite/find?o=text&u=' + (url) + '&e=*&k=' + (encodetext)  , success:Pinning.onFindPreviewPageElementLocationServiceResult});
            }, 1000);
        }
        else
        {
            var previewelement = this.findPreviewPageElement(this.currentPageElementName, this.currentPageElementLocation, text, false);
            //re-init for next hover action
            //----------------------------
            this.currentPageElementName = null;
            this.currentPageElementLocation = null;
            if (previewelement != null)
            {
                this.pin(previewelement, over);
            }
            // fall back and find macthing textnodes
            //----------------------------------------

            else
            {
                this.pinHighLightElementText(over, text);
            }
        }
    },

    onFindPreviewPageElementLocationServiceResult: function(data)

    {
        try
        {

            var elemlocation = null;
            var elemname = null;
            if (data.length > 0) // handle if response is not empty
            {
                $tigr(data).each(
                        function(index)
                        {
                            if (index == 0)
                            {
                                var nameLocation = $tigr(this).text().split("_");

                                if (nameLocation != null && nameLocation.length > 1 && nameLocation[1].trim().length > 0)
                                {
                                    elemlocation = nameLocation[1].trim();
                                }
                                if (nameLocation != null && nameLocation.length > 0 && nameLocation[0].trim().length > 0)
                                {
                                    elemname = nameLocation[0].trim();
                                }
                            }
                        }

                        );


                this.currentPageElementName = elemname;
                this.currentPageElementLocation = elemlocation;
                previewelement = Pinning.findPreviewPageElement(this.currentPageElementName, this.currentPageElementLocation, text, false);
                if (previewelement != null)
                {
                    Pinning.pin(previewelement, over);
                }
                // fall back and find macthing textnodes
                //----------------------------------------
                else
                {
                    Pinning.pinHighLightElementText(over, text);
                }
            }
            // fall back and find macthing textnodes
            //----------------------------------------
            else
            {
                Pinning.pinHighLightElementText(over, text);
            }

        }
        catch (e)
        {
            // alert("find response "+e);
        }
    },
/**
 * Mouse Hover action on each chunk of the results
 */
    hoveraction: function(elem, over, index)
    {
        try
        {
            if (!this.ENABLE_PINNING)
            {
                return false;
            }
            Preview.currentPreviewSelectedElement = elem;
            if (index != this.currentPreviewResultIndex)
            {
                return false;
            }
            var frameDocument = Preview.findPreviewDoc();
            if (this.currentPreviewURL != null && elem != null && frameDocument != null)
            {

                if (this.textPreview)
                {
                    this.pinByText($tigr(elem).text(), Preview.findPreviewWindow(), frameDocument, true);
                }
                else
                {

                    if (Pinning.lastOnloadPinElement != null && elem != Pinning.lastOnloadPinElement)
                    {
                        this.clearPin();
                        Pinning.lastOnloadPinElement = null;
                    }

                    if (!over)
                    {
                        this.clearPin();

                    }
                    else
                    {
                        //exact name and location of pinning element of preview page
                        //----------------------------------------------------------
                        var nameLocation = null;
                        //chunk type either virtual true/false
                        //--------------------------------------
                        var virtual = null;

                        nameLocation = $tigr(elem).attr("namelocation");
                        virtual = $tigr(elem).attr("virtual");
                        //call pin on the page content preview window
                        //---------------------------------------------
                        var actualName = null;
                        var elemlocation = null;

                        if (nameLocation != null)
                        {
                            var name = nameLocation.split("_");
                            var name1 = name[0].split("}");

                            if (name1 != null && name1.length > 0)
                            {
                                actualName = name1[1];
                            }
                            else
                            {
                                actualName = name[0];
                            }

                            if (name != null && name.length > 1 && name[1].trim().length > 0)
                            {
                                elemlocation = name[1];
                            }
                        }

                        var previewelement = this.findPreviewPageElement(actualName, elemlocation, $tigr(elem).text().trim(), virtual);
                        //exactly know the pinning element
                        //--------------------------------
                        if (previewelement != null && previewelement.elems != null)
                        {
                            if (previewelement.textnodes == true)
                            {
                                this.pinTextNodes(previewelement.elems);
                            }
                            else
                            {
                                this.pin(previewelement.elems, over);
                            }

                        }
                        //chunk is NOT virtual but unable to find the exact element
                        //-----------------------------------------------------------
                        else if (virtual == 'false')
                        {
                            var html = $tigr(frameDocument).html();

                            if (html != null && html.trim().length > 0 && html.trim().length > $tigr(elem).text().trim().length)
                            {
                                //invoke /yolinklite/find
                                //------------------------
                                this.findPreviewPageElementLocationService(this.currentPreviewURL, $tigr(elem).text(), html, over)
                            }
                            else
                            {
                                this.pinHighLightElementText(over, $tigr(elem).text());
                            }
                        }
                        //Chunk is virtual so fall back to finding text nodes to highlight
                        //-----------------------------------------------------------------
                        else
                        {
                            this.pinHighLightElementText(over, $tigr(elem).text());

                        }
                    }

                }
            }

        }
        catch (e)
        {
            //alert("hoveraction " + e);
        }
    },

    registerChunkNameAnchor : function(name, loc, identifier, chunkelemid, virtual)
    {
        var chunkElem = document.getElementById(chunkelemid);
        var chunktext = $tigr(chunkElem).text();
        var previewelements = this.findPreviewPageElementByNameAndText(chunktext, name, loc, document, virtual);
        var pinelem = null;
        if (previewelements != null && previewelements.elems != null)
        {
            if (previewelements.textnodes == true)
            {
                pinelem = previewelements.elems[0];
            }
            else
            {
                pinelem = previewelements.elems;
            }

        }
        else
        {
            this.pinByText(chunktext, window, document, true);
            /*var textnodes = $tigr(document).findMatchingTextNodeParents(chunktext);
          if (textnodes.length > 0)
          {
          previewelements = {textnodes:true,elems:textnodes};
          pinelem = textnodes[0];
          }
          else
          {
          this.pinByText(chunktext, window, document);
          }  */

        }

        if (pinelem != null)
        {
            var matched = false;
            //find if the content to pin is a parent of the current chunk
            //no anchor if it is true
            //-----------------------------------------------------------
            if ($tigr('#' + chunkelemid).parents().index(pinelem) >= 0)
            {
                matched = true;
            }
            if (!matched)
            {
                /* if (pinelem != null)
                {
                $tigr('<a name=\"' + identifier + '\" id=\"' + identifier + '\" />').insertBefore(pinelem);
                }*/

                if (this.lastInlineElementPinned != null)
                {
                    this.inlinepin(false);
                }
                this.lastInlineElementPinned = previewelements;
                this.inlinepin(true);
            }

        }


    },
    pinByText : function(query, preview_window, preview_doc, deletePrevSelection)
    {
        try
        {
            var found = false;
            var sel;
            var range;
            var caseSensitive = false;
            var previewContent = preview_window;
            //replace elipses only if they are in very start of chunk
            if (query.indexOf("...") == 0)
            {
                query = query.replace("...", "");
            }
            else
                if (query.indexOf("..") == 0)
                {
                    query = query.replace("..", "");
                }

            var stripSpaceQuery = query.replace(/\n/g, "");
            try
            {
                sel = previewContent.getSelection();
            }
            catch(e)
            {

                /* try IE search */
                this.pinByText_IE(query, preview_doc, deletePrevSelection);
                return false;
            }

            if (deletePrevSelection == true)
            {
                if (sel.rangeCount > 0)
                {
                    sel.removeAllRanges();
                }
            }
            if (range)
            {
                sel.addRange(range);
            }


            //this.strip(query);
            found = previewContent.find(stripSpaceQuery, caseSensitive, false);
            if (!found)
            {
                found = previewContent.find(stripSpaceQuery, caseSensitive, true);
            }

            if (!found)
            {
                found = previewContent.find(query, caseSensitive, false);
            }

            if (!found)
            {
                found = previewContent.find(query, caseSensitive, true);
            }
            if (!found)
            {
                if (query.split("\r").length > 0)
                {
                    newText = query.split("\r")[0];
                    found = previewContent.find(newText, false, false);
                    if (!found)
                    {
                        found = previewContent.find(newText, false, true);
                    }
                }
            }
            if (!found)
            {
                if (query.split("\.").length > 0)
                {
                    newText = query.split("\.")[0];
                    found = previewContent.find(newText, false, false);
                    if (!found)
                    {
                        found = previewContent.find(newText, false, true);
                    }
                }

            }
            if (!found)
            {
                if (query.length > 49)
                {
                    newText = query.substring(0, 50);
                    found = previewContent.find(newText, false, false);
                    if (!found)
                    {
                        found = previewContent.find(newText, false, true);
                    }
                }

            }
            if (!found)
            {
                if (query.length > 49)
                {
                    newText = query.substring(0, 10);
                    found = previewContent.find(newText, false, false);
                    if (!found)
                    {
                        found = previewContent.find(newText, false, true);
                    }

                }

            }

            this.finds++;

            sel = window.getSelection();
            return found;
        }
        catch(e)
        {
            //alert(' findText err ' + e);
        }
    },

    pinByText_IE:function(query, previewdoc, scrollIntoView)
    {

        try
        {

            var stripSpaceQuery

            var range = previewdoc.body.createTextRange();
            var found = range.findText(query);
            var stripSpaceQuery ;

            if (!found)
            {
                stripSpaceQuery = query.replace(/\n/g, "");
                found = range.findText(stripSpaceQuery);
            }
            if (!found)
            {
                if (query.split("\n").length > 0)
                {
                    newText = query.split("\n")[0];
                    found = range.findText(newText);
                }
            }
            if (!found)
            {
                if (query.split("\r").length > 0)
                {
                    newText = query.split("\r")[0];
                    found = range.findText(newText);
                }
            }

            if (!found)
            {
                if (query.split("\.").length > 0)
                {
                    newText = query.split("\.")[0];
                    found = range.findText(newText);
                }

            }

            if (!found)
            {
                if (query.length > 49)
                {
                    newText = query.substring(0, 50);
                    found = range.findText(newText);
                }

            }

            if (!found)
            {
                if (query.length > 49)
                {
                    newText = query.substring(0, 10);
                    found = range.findText(newText);
                }


            }
            var selectedTextLength = range.text.length;
            var forwardMoveBy = query.length - selectedTextLength;
            range.moveEnd("character", forwardMoveBy);

            range.select();
            if (scrollIntoView == true)
            {
                range.scrollIntoView();
            }
        }
        catch(e)
        {
            // alert(' in IE findText err ' + e);
        }

    }


}
//------------------------------------------------
//Page Preview Related functions
//------------------------------------------------
Preview =
{
//Window size Parameters for drag boundary computations
//------------------------------------------------------------
    windowMinWidth: 100,
    windowMinHeight: 100,
    windowWidth : 0,
    windowHeight : 0,
    windowTop : 0,
    windowLeft : 0,
    divWidth : 0,
    divHeight : 0,
    newdragTop:50,
    newdragLeft: (window.innerWidth || document.documentElement.clientWidth) / 2.5,
    ///optimizeDrag , by default false and window position changes as user drags the window, 
    //when set to true, window position changes only after mouseup.
    //---------------------------------------------------------------------------------------
    optimizeDrag:false, 
    isResizeing: false,
    resizingWindowWidth:0,
    resizingWindowHeight:0,
    currentPreviewSelectedElement:null,
    previewdivs : "<div id=\"preview_div_back\" style=\"display:none;\"> </div>" +
                  "<div id=\"preview_div\" style=\"display:none;\"> </div>",
    proxyURL:getYoProp('server') + "/yolinklite/proxy-page?u=",
    previewStyleURL: getYoProp('server') + "/yolinklite/css/toolbar.css",
    ipadpreviewStyleURL: getYoProp('server') + "/yolinklite/css/ipad-preview.css",
    useCrossDomain:true,
    istartX:0,
    istartY:0,
    ifrTouchStarted:false,
    ifrLastTop:0,
    ifrLastLeft :0,
    ifrTouchEvntX:0,
    ifrTouchEvntY:0,
    initialize : function(argPreviewStyleURL)
    {
        try
        {

            var previewDivBack = document.getElementById('preview_div_back');
            if (previewDivBack == null)
            {
                var bodyelem = document.getElementsByTagName('body')[0];
                $tigr(bodyelem).append(this.previewdivs);
            }

            if (typeof argPreviewStyleURL != 'undefined')
            {
                this.previewStyleURL = argPreviewStyleURL;
            }

        }
        catch (e)
        {
            //alert("initialize "+e);
        }
    },

    registerTextPreviewAction : function(elem, url, previewelemname, previewelemlocation, index)
    {
        $tigr(elem).attr('namelocation', previewelemname);
        $tigr(elem).attr('virtual', previewelemlocation);
        $tigr(elem).mouseover(function ()
        {
            Pinning.hoveraction(this, true, index);
        });
        $tigr(elem).mouseout(function ()
        {
            Pinning.hoveraction(this, false, index);
        });
        $tigr(elem).attr('href', "javascript:Preview.preview('" + index + "', '" + tigr.util.encodeNescapeSingleQuote(url) + "',true, this);");
        try
        {
            elem.addEventListener("touchstart", this.touchStart, false);
        }
        catch (e)
        {

        }
    },
    registerPreviewAction : function(elem, url, previewelemname, previewelemlocation, index, contenttype)
    {
        $tigr(elem).attr('namelocation', previewelemname);
        $tigr(elem).attr('virtual', previewelemlocation);
        $tigr(elem).mouseover(function ()
        {
            Pinning.hoveraction(this, true, index);
        });
        $tigr(elem).mouseout(function ()
        {
            Pinning.hoveraction(this, false, index);
        });
        $tigr(elem).attr('href', "javascript:Preview.preview('" + index + "', '" + tigr.util.encodeNescapeSingleQuote(url) + "','" + contenttype + "', this);");

        try
        {
            elem.addEventListener("touchstart", this.touchStart, false);
        }
        catch (e)
        {

        }

    },
    registerInlinePreviewAction : function(elem, elemid, previewelemname, virtual)
    {
        var actualName = null;
        var elemlocation = null;
        if (previewelemname != null)
        {
            var name = previewelemname.split("_");
            var name1 = name[0].split("}");

            if (name1 != null && name1.length > 0)
            {
                actualName = name1[1];
            }
            else
            {
                actualName = name[0];
            }

            if (name != null && name.length > 1 && name[1].trim().length > 0)
            {
                elemlocation = name[1];
            }
        }


        $tigr(elem).mouseover(function ()
        {
            Pinning.registerChunkNameAnchor(actualName, elemlocation, "", elemid, virtual);

        });
        $tigr(elem).mouseout(function ()
        {
            Pinning.inlinepin(false);
        });

    },
/**
 * preview iframe widnow handle for find by text
 */
    findPreviewWindow : function()
    {
        var docwindow = null;
        try
        {
            var fname = $tigr.browser.iPad == true ? 'yopadpreview_frame' : 'preview_frame';
            var previewFrame = document.getElementById(fname);
            if (previewFrame != null)
            {
                if (previewFrame.contentWindow)
                {
                    docwindow = previewFrame.contentWindow;
                }
                else
                {
                    docwindow = previewFrame;
                }
            }

        }
        catch (e)
        {
            docwindow = null;
        }
        return docwindow;
    },
/**
 *find preview frame document object
 */
    findPreviewDoc : function()
    {
        var docElm = null;
        try
        {
            var fname = $tigr.browser.iPad == true ? 'yopadpreview_frame' : 'preview_frame';
            var previewFrame = document.getElementById(fname);
            if (previewFrame != null)
            {
                if (previewFrame.contentWindow)
                {
                    docElm = previewFrame.contentWindow.document;
                }
                else
                {
                    docElm = previewFrame.contentDocument;
                }
            }

        }
        catch (e)
        {
            //may be permission denied error
            //no pinning
            //------------------------------
            docElm = null;
        }
        return docElm;
    },
    previewframeLoaded: function(index)
    {
        if ($tigr.browser.iPad == true)
        {
            Pinning.pinAllPreviewPageElementsByNameAndText($tigr('a[name=chunk-link][resultindex=' +  Pinning.currentPreviewResultIndex + ']'), this.findPreviewDoc());
            this.ipadOnLoad();
        }
        else
        {
            //IE Quirks mode: set back frame width and height to 100% 
            //-------------------------------------------------------
            if (!tigr.util.IESupportsModernCSS(document))
            {
               // var heightpercent = (( ($tigr("#preview_frame").height()+4)/$tigr("#preview_frame_div").height())*100);
               //  var widthpercent = (( ($tigr("#preview_frame").width()+4)/$tigr("#preview_frame_div").width())*100);
                $tigr('#preview_frame').css("height", "100%");
                $tigr('#preview_frame').css("width", "100%");
            }
            if (this.currentPreviewSelectedElement != null)
            {
                Pinning.lastOnloadPinElement = this.currentPreviewSelectedElement;
                Pinning.hoveraction(this.currentPreviewSelectedElement, true, index);
            }
            //E3709:bind mouse up call back on preview iframe document
            //--------------------------------------------------------
            var previewframedoc = this.findPreviewDoc();
            if (previewframedoc != null)
            {
                $tigr(previewframedoc).mouseup(function(e)
                {
                    return $tigr.mouseUpOfCurrentMouseEvent(e);
                });

            }
        }
    },

    injectCSS : function()
    {
        var doc = Preview.findPreviewDoc();
        if (doc != null)
        {
            var head = doc.getElementsByTagName('head')[0] || doc.documentElement;
            var link = doc.createElement('link');
            // alert((($tigr.browser.iPad == true)? Preview.ipadpreviewStyleURL:Preview.previewStyleURL) );
            link.setAttribute('href', (($tigr.browser.iPad == true)? Preview.ipadpreviewStyleURL:Preview.previewStyleURL));
            link.setAttribute('media', 'screen');
            link.setAttribute('type', 'text/css');
            link.setAttribute('rel', 'stylesheet');
            head.appendChild(link);
            //call pinning after css is injected
            //------------------------------------
            this.previewframeLoaded(Pinning.currentPreviewResultIndex);
        }

    },

//
// Callback for cross-domain call to get HTML document for the iframe.
//
    onResult : function(result)
    {
        if( typeof(result) == 'object' )
        {
            result = result.value;
        }
        if (result && result.length > 0)
        {
            var doc = Preview.findPreviewDoc();

            if (doc)
            {
                var sb = new tigr.util.StringBuffer();
                if (Pinning.textPreview)
                {
                    sb.append("<pre>");
                    sb.append(result);
                    sb.append("</pre>");
                    sb.append('<script type="text/javascript">window.parent.Preview.previewframeLoaded(');
                    sb.append(Pinning.currentPreviewResultIndex);
                    sb.append(');</script>');
                }
                else
                {
                    sb.append(result);
                    sb.append('<script type="text/javascript">window.parent.Preview.injectCSS();</script>');
                }
                doc.write(sb.toString());
            }
        }
        else
        {
            this.injectCSS();
        }


    },

//
// Called from iframe onload event.
// If <code>src</code> is not empty, then we need to do a cross-domain call
// to get the HTML document.
//
    iFrameOnLoad : function(src)
    {
        if (src && src.length > 0)
        {
            setTimeout(function()
            {
                $tigr.xget({url:src, success:Preview.onResult});
            }, 1000);
        }
        else
        {
            Preview.onResult('');
        }
    },


    ipadOnLoad : function()
    {
        try
        {
            var iframewidth = $tigr('#yopadpreview_frame').width();
            var iframeheight = $tigr('#yopadpreview_frame').height();
            //hack to make sure , it renders the border around iframe content
            //when iframe height > 1024
            //---------------------------------------------------------------
            if (iframeheight > 1024 && iframeheight < 5000)
            {
                iframeheight += 125;
            }
            else if (iframeheight >= 5000)
            {
                iframeheight += 250;
            }
            var previewdivwidth = iframewidth + 24 + 8 + 8;
            var previewdivheight = iframeheight + 24 + 50 + 10;


            var previewinnerdivheight = iframeheight;
            var previewinnerdivwidth = iframewidth ;

            var previewinnerdivheightpercent = ( (previewinnerdivheight / previewdivheight) * 100);
            var previewinnerdivwidthpercent = ( (previewinnerdivwidth / previewdivwidth) * 100);

            var resizeImageDivTop = previewdivheight - 10;
            var resizeImageWidth = previewdivwidth - 8;


            $tigr('#yopadpreview_div').css('width', previewdivwidth + "px");
            $tigr('#yopadpreview_div').css('height', previewdivheight + "px");

            $tigr('#yopadpreview_div_back').css('width', previewdivwidth + "px");
            $tigr('#yopadpreview_div_back').css('height', previewdivheight + "px");

            $tigr('#yopadpreview_div').css('min-width', previewdivwidth + "px");
            $tigr('#yopadpreview_div').css('min-height', previewdivheight + "px");

            $tigr('#yopadpreview_div_back').css('min-width', previewdivwidth + "px");
            $tigr('#yopadpreview_div_back').css('min-height', previewdivheight + "px");

            $tigr('#yopadpreview_frame_div').css("height", previewinnerdivheight + "px");
            $tigr('#yopadpreview_frame_div').css("width", previewinnerdivwidth + "px");

            $tigr('#yopadpreview_frame_div').css("min-height", previewinnerdivheight + "px");
            $tigr('#yopadpreview_frame_div').css("min-width", previewinnerdivwidth + "px");

            /*
           $tigr('#preview_frame_div').css("height", previewinnerdivheightpercent + "%");
           $tigr('#preview_frame_div').css("width", previewinnerdivwidthpercent + "%");
           $tigr('#preview_frame_div').css("min-height", previewinnerdivheightpercent + "%");
           $tigr('#preview_frame_div').css("min-width", previewinnerdivwidthpercent + "%");


           $tigr('#preview_bottom_resize').css("top", resizeImageDivTop);
           $tigr('#preview_bottom_resize').css("left", '8px');
           $tigr('#preview_bottom_resize').css("width", resizeImageWidth);
           $tigr('#preview_bottom_resize').css("height", "10px");*/

            $tigr('#yopadpreview_frame').show();

        }
        catch (e)
        {
            //   alert("ipadOnLoad:"+e);
        }

    },
/**
 * on chunk element touch start
 */
    touchStart : function(event)
    {
        this.istartX = event.touches[0].pageX;
        this.istartY = event.touches[0].pageY;
    },

/**
 * ipad preview div on touch start
 */
    ifrtouchStart : function(event)
    {

        this.ifrTouchEvntX = event.targetTouches[0].pageX;
        this.ifrTouchEvntY = event.targetTouches[0].pageY;

        this.ifrLastTop = $tigr('#yopadpreview_div').css("top");
        this.ifrLastLeft = $tigr('#yopadpreview_div').css("left");

        if (this.ifrLastTop != null && this.ifrLastTop.indexOf("px") >= 0)
        {
            this.ifrLastTop = this.ifrLastTop.substring(0, this.ifrLastTop.indexOf("px"));
        }
        if (this.ifrLastLeft != null && this.ifrLastLeft.indexOf("px") >= 0)
        {
            this.ifrLastLeft = this.ifrLastLeft.substring(0, this.ifrLastLeft.indexOf("px"));
        }
        this.ifrTouchStarted = true;
    },
/**
 * ipad preview div on touch move
 */
    ifrtouchMove :function(event)
    {
        try
        {
            if (this.ifrTouchStarted)
            {
                event.preventDefault();
                var padding = 20;
                var curX = event.targetTouches[0].pageX ;
                var curY = event.targetTouches[0].pageY ;

                var movedX = (curX - this.ifrTouchEvntX);
                var movedY = (curY - this.ifrTouchEvntY);

                var leftX = (parseInt(this.ifrLastLeft) + movedX) ;
                var topY = (parseInt(this.ifrLastTop) + movedY);

                var ifrwidth = $tigr('#yopadpreview_div').width();
                if (ifrwidth < $tigr('#yopadpreviewframe').width())
                {
                    ifrwidth = $tigr('#yopadpreviewframe').width() + 24 + 8 + 8;
                }
                var ifrheight = $tigr('#yopadpreview_div').height();
                if (ifrheight < $tigr('#yopadpreviewframe').height())
                {
                    ifrheight = $tigr('#yopadpreviewframe').height() + 24 + 50 + 10;
                }


                var rightX = leftX + ifrwidth  ;
                //Preview.divWidth;
                var bottomY = topY + ifrheight;
                var updateDivs = false;

                //leftx < leftX of window or rightx > rightX of window
                //topy < topX of Window or bottomY > bottomX of window
                //Check drag boundary
                //----------------------

                if ((rightX > (Preview.windowLeft + 50) ) && ( leftX < (Preview.windowLeft + Preview.windowWidth - 50)))   //left and right limits
                {
                    updateDivs = true;
                }
                if ((updateDivs == true) && ( bottomY > 0 && ( bottomY > (Preview.windowTop + 70)))
                        && ( topY < (Preview.windowTop + Preview.windowHeight - 70))) //top and bottom limits
                {
                    updateDivs = true;
                }
                else
                {

                    updateDivs = false;

                }

                if (updateDivs)
                {

                    $tigr('#yopadpreview_div').css("top", (topY));
                    $tigr('#yopadpreview_div').css("left", (leftX));
                    $tigr('#yopadpreview_div_back').css("top", (topY));
                    $tigr('#yopadpreview_div_back').css("left", (leftX));

                    this.ifrLastLeft = leftX;
                    this.ifrLastTop = topY;
                }

            }

        }
        catch (e)
        {
            // alert(e)
        }
    },



/**
 * ipad preview div on touch end
 */
    ifrtouchEnd :function(event)
    {
        this.ifrTouchStarted = false;
        ;

    },
/**
 * ipad preview div on close
 */
    ifrclosePreview : function()
    {
        if ($tigr('#yopadpreview_div') != null)
        {
            $tigr('#yopadpreview_div_back').remove();
            $tigr('#yopadpreview_div').remove();
        }
        // this.istartX = 0;
        // this.istartY = 0;
    },
/**
 * opens ipad preview window for the given url
 */
    ipadPreview: function(src, prevURL, url)
    {
        try
        {
            this.ifrclosePreview();
            var shortenURL = url;
            if (shortenURL.length > 40)
            {
                shortenURL = shortenURL.substring(0, 40) + "...";
            }

            var ht = [];
            var i = 0;
            ht[i++] = '<div id="yopadpreview_div_back" > </div>';
            ht[i++] = '<div id="yopadpreview_div" ontouchstart="Preview.ifrtouchStart(event);" ontouchmove="Preview.ifrtouchMove(event);" ontouchend="Preview.ifrtouchEnd(event);">';
            ht[i++] = '<div id="yopadpreview_legend" >';
            ht[i++] = '&nbsp;&nbsp;<a class="yopad_previewclose" href="javascript:Preview.ifrclosePreview();"><img border="0" src="' + getYoProp('server') + '/yolinklite/images/exit.png" /></a>&nbsp;&nbsp;';
            ht[i++] = '<span class="yopad_inlegend_div">Preview of <a  class="yopad_inlegend" href="' + url + '">' + shortenURL + '</a></span><br/></div>';
            ht[i++] = '<div id="yopadpreview_frame_div" class="yopadpreview_frame_div"><iframe name="yopadpreview_frame" id="yopadpreview_frame" style="display:none" class="yopadpreview_frame" src="' + (src.length == 0 ? prevURL : '') + '"  scrolling="auto" onload="Preview.iFrameOnLoad(\'' + src + '\');"></iframe></div>';
            ht[i++] = '</div>';

            $tigr('body:first').append(ht.join(' '));

            $tigr('#yopadpreview_div_back').css("top", this.istartY);
            $tigr('#yopadpreview_div_back').css("left", this.istartX);
            $tigr('#yopadpreview_div').css("top", this.istartY);
            $tigr('#yopadpreview_div').css("left", this.istartX);

            var w = $tigr('#yopadpreview_div').width();
            var h = $tigr('#yopadpreview_div').height();

            $tigr('#yopadpreview_frame').css('width', (w - 40) + 'px');
            $tigr('#yopadpreview_frame').css('height', (h - 24 - 50 - 10) + 'px');


        }
        catch (e)
        {
            //alert("ipadPreview"+e);
        }
    },

    preview: function(index, url, contenttype)
    {

        this.initWindowBoundaries();
        this.closePreview(false);
        var isPdf = false;
        if (contenttype != null && contenttype == "text/plain")
        {
            Pinning.textPreview = true;
        }
        // #3825 If it is pdf we do not want to render text through it just keep the url as is and let the frame load it
        // ----------------------------------------------------
        else if (contenttype != null && contenttype == "application/pdf")
        {
            Pinning.textPreview = false;
            isPdf = true;
        }
        else
        {
            Pinning.textPreview = false;
        }

        Pinning.currentPreviewURL = url;
        Pinning.currentPreviewResultIndex = index;
        var shortenURL = url;
        if (shortenURL.length > 60)
        {
            shortenURL = shortenURL.substring(0, 60) + "...";
        }

        var prevURL = null;
        var src = '';

        // Disable pinning for IE7 because of cross-domain issue.
        //var isIE7 = ($tigr.browser.msie && ($tigr.browser.version < 8));
        if (isPdf === true)
        {
            prevURL = Pinning.currentPreviewURL;
        }
        else if (tigr.util.isSameDomain(url))
        {
            //E3771: same url does not load on ff and ie.
            //-------------------------------------------
            if (($tigr.browser.msie || $tigr.browser.mozilla) && (url == document.location ))
            {
                prevURL = this.proxyURL + encodeURIComponent(Pinning.currentPreviewURL);
                src = prevURL;
            }
            else
            {
                prevURL = Pinning.currentPreviewURL;
            }
        }
        else if (!this.useCrossDomain)
        {
            prevURL = this.proxyURL + encodeURIComponent(Pinning.currentPreviewURL);
        }
        else
        {
            prevURL = this.proxyURL + encodeURIComponent(Pinning.currentPreviewURL);
            src = prevURL;
        }

        if ($tigr.browser.iPad == true)
        {
            this.ipadPreview(src, prevURL, url);
            return;
        }
        var legend =
                '<div id="preview_legend" ><span class="yo_legend preview_ellipsis">' +
                '&nbsp;&nbsp;<a class="yo_previewclose" href="javascript:Preview.closePreview(true);"><img border="0" src="' + getYoProp('server') + '/yolinklite/images/btn_close.png" /></a>&nbsp;&nbsp;' +
                'Preview of <a  class="yo_inlegend" href="' + url + '">' + shortenURL + '</a><br/></span></div>';
        var previewDiv = $tigr('#preview_div');
        var previewDivBack = $tigr('#preview_div_back');
        $tigr(previewDiv).append(legend);
        $tigr(previewDiv).append('<div id="preview_frame_div" class="preview_frame_div"><iframe name="preview_frame" id="preview_frame" class="preview_frame" src="' + (src.length == 0 ? prevURL : '') + '"  scrolling="auto" onload="Preview.iFrameOnLoad(\'' + src + '\');"></iframe></div><div id="preview_bottom_resize"><img class="preview_resize_image" src="' + getYoProp('server') + '/yolinklite/images/bottom_right.png" onmousedown="Preview.initResizeWinPositions()"/></div>');
        //IE Quirks Mode: load the preview window at the location of the chunk element
        //-----------------------------------------------------------------------------
        if (!tigr.util.IESupportsModernCSS(document) && Preview.currentPreviewSelectedElement != null)
        {
            var prevElemY =  $tigr(Preview.currentPreviewSelectedElement).position().top;
            $tigr('#preview_div_back').css("top", prevElemY+"px");
            $tigr('#preview_div').css("top", prevElemY+"px");
        }

        $tigr(previewDivBack).fadeIn('slow');
        $tigr(previewDiv).fadeIn('slow');
        //enable drag on preview window
        //-----------------------------
        $tigr(previewDiv).enablePreviewDrag();
        
        if (Preview.resizingWindowWidth > 0)
        {
            this.setNewWinPositions(Preview.resizingWindowWidth, Preview.resizingWindowHeight);
        }
    }
    ,
/*
* closes the preview window
*/
    closePreview: function(isclosed)
    {
        Pinning.currentPreviewURL = null;
        Pinning.currentPreviewResultIndex = -1;
        this.applyPreviewCssOnClose();
        $tigr('#preview_legend').remove();
        $tigr('#preview_frame_div').remove();
        $tigr('#preview_bottom_resize').remove();
        if (!$tigr.browser.msie)
        {
            $tigr('#preview_div_back').fadeOut('slow');
            $tigr('#preview_div').fadeOut('slow');
           
        }
        else if (isclosed && $tigr.browser.msie)
        {
            $tigr('#preview_div_back').fadeOut(300);
            $tigr('#preview_div').fadeOut(300);
            
        }

    }
    ,
    readPreviewWinPosition : function()
    {
        var winposcookie = tigr.util.readCookie("cloudyolinkpreviewwinpositions");
        if (winposcookie)
        {
            var winpositions = winposcookie.split(":");
            this.newdragTop = winpositions[0];
            this.newdragLeft = winpositions[1];
        }
    },
    savePreviewWinPosition : function()
    {
        $tigr.util.createCookie("cloudyolinkpreviewwinpositions", Preview.newdragTop + ":" + Preview.newdragLeft, 365);
    }
    ,
/**
 * resets the css for preview window . may be the css got modified during the drag
 */
    applyPreviewCssOnClose : function()
    {
        $tigr('#preview_div_back').addClass("preview_div_back");
        $tigr('#preview_div').addClass("preview_div");
        $tigr('#preview_frame_div').addClass("preview_frame_div");
        $tigr('#preview_frame').addClass("preview_frame");
        $tigr('#preview_bottom_resize').addClass("#preview_bottom_resize");

        if ($tigr.browser.msie)
        {
            $tigr('#preview_div_back').css("display", 'block');
        }

        $tigr('#preview_div_back').css("top", Preview.newdragTop);
        $tigr('#preview_div_back').css("left", Preview.newdragLeft);
        $tigr('#preview_div').css("top", Preview.newdragTop);
        $tigr('#preview_div').css("left", Preview.newdragLeft);


    }
    ,

/**
 * computes window size parameters
 */
    initWindowBoundaries : function()
    {

        if (typeof( window.innerWidth ) == 'number')
        {
            //Non-IE
            this.windowWidth = window.innerWidth;
            this.windowHeight = window.innerHeight;

        }
        else if (document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ))
        {
            //IE 6+ in 'standards compliant mode'
            this.windowWidth = document.documentElement.clientWidth;
            this.windowHeight = document.documentElement.clientHeight;
        }
        else if (document.body && ( document.body.clientWidth || document.body.clientHeight ))
        {
            //IE 4 compatible
            this.windowWidth = document.body.clientWidth;
            this.windowHeight = document.body.clientHeight;
        }

        if (typeof( window.screenX ) == 'number')
        {
            //Netscape compliant
            this.windowLeft = window.screenX;
            this.windowTop = window.screenY;
        }
        else   if (typeof( window.screenLeft ) == 'number')
        {
            //Netscape compliant
            this.windowLeft = window.screenLeft;
            this.windowTop = window.screenTop;
        }
        this.divWidth = 800;
        this.divHeight = 600;
        //IE Quirks mode:set newdragLeft to pisiton window to the right
        //-------------------------------------------------------------
        if(this.newdragLeft == 0)
        {
            this.newdragLeft =  (this.windowWidth) / 2.5;
        }
        //IE Quirks Mode: The window height needs to be the document height
        //In Quriks mode, IE fixes any popup window and moving on scroll bars, won't keep the
        //window on top of the view port where as all other browsers keeps the popups on top of view port
        //so scrolling using scroll bars on other browsers won't change preview window position.
        //so this is required to allow correct drag position in relation to the chunk location where it is opened
        //--------------------------------------------------------------------------------------------------------
        if(  !tigr.util.IESupportsModernCSS(document))
        {
            this.windowHeight = $tigr(document).height();
        }
    } ,
    initResizeWinPositions : function()
    {
        this.isResizeing = true;
        if (this.resizingWindowWidth == 0)
        {
            this.resizingWindowWidth = this.divWidth;
            this.resizingWindowHeight = this.divHeight;
        }
        else
        {

            this.resizingWindowWidth = $tigr('#preview_div_back').width();
            this.resizingWindowHeight = $tigr('#preview_div_back').height();
        }
        
        $tigr('#preview_frame_div').prepend('<div id="overlay_iframe_fix" style="width:' + this.resizingWindowWidth + 'px; height:' + this.resizingWindowHeight + 'px; position: absolute; top:0px; left:0px; background-color: transparent; z-index:9999999999;"> <img src="' + getYoProp('server') + '/yolinklite/images/1x1transparent.png" style="width: 100%; height: 100%;"/> </div>');
        $tigr('body:first').append('<div id="overlay_iframe_fix_body" style="width:100%; height:100%; position: absolute; top:0px; left:0px; background-color: transparent; z-index:999875;"> <img src="' + getYoProp('server') + '/yolinklite/images/1x1transparent.png" style="width: 100%; height: 102%;"/> </div>');
        
    },

    setNewWinPositions : function(newWidth, newHeight)
    {
        //24 -- 2*iframe broder 12px
        //30 -- top margin for iframe div
        //10 bottom margin
        //8 left , right margins
        //-----------------------------------
        if ($tigr('#overlay_iframe_fix') != null)
        {
            $tigr('#overlay_iframe_fix').css('width', newWidth - 28).css('height', newHeight - 52);
        }
        try
        {
            var previewinnerdivheight = newHeight - 24 - 30 - 10;
            var previewinnerdivwidth = newWidth - 24 - 8 - 8 ;
            //for Quirks mode omit div border (24)  
            //------------------------------------
            if (!tigr.util.IESupportsModernCSS(document))
            {
                previewinnerdivheight = newHeight - 30 - 10;
                previewinnerdivwidth = newWidth  - 8 - 8 ;
            }

            var previewinnerdivheightpercent = ( (previewinnerdivheight / newHeight) * 100);
            var previewinnerdivwidthpercent = ( (previewinnerdivwidth / newWidth) * 100);

            var resizeImageDivTop = newHeight - 10;
            var resizeImageWidth = newWidth - 8;

            $tigr('#preview_div_back').css("width", newWidth);
            $tigr('#preview_div_back').css("height", newHeight);
            if (tigr.util.IESupportsModernCSS(document))
            {  
                $tigr('#preview_div').css("position", 'fixed');
            }
            else
            {
                $tigr('#preview_div').css("position", 'absolute');
            }
            $tigr('#preview_div').css("width", newWidth);
            $tigr('#preview_div').css("height", newHeight);

            $tigr('#preview_frame_div').css("position", 'absolute');

            $tigr('#preview_frame_div').css("height", previewinnerdivheightpercent + "%");
            $tigr('#preview_frame_div').css("width", previewinnerdivwidthpercent + "%");

            $tigr('#preview_frame').css("position", 'absolute');

            $tigr('#preview_bottom_resize').css("position", "absolute");
            $tigr('#preview_bottom_resize').css("top", resizeImageDivTop);
            $tigr('#preview_bottom_resize').css("left", '8px');
            $tigr('#preview_bottom_resize').css("width", resizeImageWidth);
            $tigr('#preview_bottom_resize').css("height", "10x");
        }
        catch (e)
        {
            //alert(e);
        }
    }


}


$tigr(document).ready(function()
{
    //Preview.readPreviewWinPosition();

    // at read tyime, we want to be sure that whomever is loading this supports and is IE
    // will support modern css calls and essentially is not in quirks mode.  If it doesn't
    // support modern functionality, then we have to override certain methods (or in this case,
    // function properties.  Below is the properties we wish to override
    if (!tigr.util.IESupportsModernCSS(document))
    {
        Preview.applyPreviewCssOnClose = function()
        {
            $tigr('#preview_div_back').addClass("preview_div_back");
            $tigr('#preview_div').addClass("preview_div");
            $tigr('#preview_frame_div').addClass("preview_frame_div");
            $tigr('#preview_frame').addClass("preview_frame");
            $tigr('#preview_bottom_resize').addClass("#preview_bottom_resize");

            if ($tigr.browser.msie)
            {
                $tigr('#preview_div_back').css("display", 'block');
            }

            $tigr('#preview_div_back').css("top", Preview.newdragTop);
            $tigr('#preview_div_back').css("left", Preview.newdragLeft);
            $tigr('#preview_div').css("top", Preview.newdragTop);
            $tigr('#preview_div').css("left", Preview.newdragLeft);
        }
        //attach the scroll function and reposition the preview page when the person scrolls. On quirks mode
        // fixed position does  not work so we have to calculate it ourselves
        // -----------------------------------------------------------
      /* $tigr(window).scroll(function()
        {
            var position = $tigr().maintainRelativePosition($tigr('#preview_div'));
            var positionB = $tigr().maintainRelativePosition($tigr('#preview_div_back'));
            if( position && positionB )
            {
               $tigr('#preview_div').css({'left':position.x + 'px', 'top': position.y + 'px'})
               $tigr('#preview_div_back').css({'left':positionB.x + 'px', 'top': positionB.y + 'px'})
            }
         });*/
       
    }
});


/*$tigr(window).unload(function()
{
	Preview.savePreviewWinPosition();
});*/
//------------------------------------------------
//PopOver window Related functions
//------------------------------------------------
PopOver = {
    //Properties
    resultsContainer : null,
    popoverContainer : null,
    options          : null,
    anchorMap        : [],
    draggable        : false,

    //takes options value from toolbar, if no args are passed then options will not be rendered to popover
    init : function(args)
    {
        this.options = args;

        var html =[];
        html.push('<div id="yolink_popover_container">');
        html.push('    <div id="yolink_popover_container_title">');
        html.push('        <img class="popover_logo"src="http://raindata.vo.llnwd.net/o25/yolink/images/iframelogo.png" alt="Yolink" onclick="yolink.App.goHome()" />');
        html.push('        <div id="yolink_popover_options"></div>');
        html.push('        <div class="yolink_container_title_menu">');
        html.push('         <a title="Hide yolink Results" id="popover_hide_show" class="yolinkCloseButtonBottom" href="javascript:PopOver.showHideToggle()"></a>');
        html.push('        </div>');
        html.push('    </div>');
        html.push('    <hr/>');
        html.push('    <ul id="yolink_popover_results">');
        html.push('    </ul>');
        html.push('</div>');

        $tigr(document.body).append(html.join(''));

        var that = this;
        that.resultsContainer = $tigr('#yolink_popover_results');
        that.popoverContainer = $tigr('#yolink_popover_container');

        // HACK - Sometimes the jquery.ui scripts have not been loaded yet, so .draggable will fail and take a number
        //        of things with it. So, insert a guard and try it again later if it fails.
        that._makeDraggable();

        if(args)
        {
            // README: are not rendering the options on the popover at the moment.
            // -----------------------------------------------------------
            that.renderOptions();
        }
        //Set Popup height
        that.onResize();

        //Binds onresize event to function
        $tigr(window).resize(
            function()
            {
                PopOver.onResize();
            });
    },
    renderOptions:function()
    {

        // Add optional stuff.
        a = [];
        i = 0;

        if (PopOver.options.checkboxes)
        {
            a[i++] = '<input id="check_all" title="Select/Deselect all results" type="checkbox" onclick="Checkbox.selectAll(this);"/>';
        }

        if (PopOver.options.bookmark)
        {
            a[i++] = '<span class="yo_options">';
            a[i++] = '<img title="Click to bookmark selected results" alt="Click to bookmark selected results" src="'+getYoProp('server')+'/yolinklite/images/transbmarkicon311.png" style="cursor:pointer;" ';
            a[i++] = 'onmouseout="img_mouseover(this);" onmouseover="img_mouseover(this);" onclick="yolink.cloud.Widget.doBookmark();"/>';
            a[i++] = '</span>';
        }

        if (PopOver.options.share)
        {
            a[i++] = '<span class="yo_options">';
            a[i++] = '<img title="Click to share selected results to Social Networks Research Services and Email" alt="Click to share selected results to Social Networks, Research Services and Email" src="'+getYoProp('server')+'/yolinklite/images/transsharesmallgrey311.png" style="cursor:pointer;" ';
            a[i++] = 'onmouseout="img_mouseover(this);" onmouseover="img_mouseover(this);" onclick="yolink.cloud.Widget.doSocial();"/>';
            a[i++] = '</span>';
        }

        if (PopOver.options.googledocs)
        {
            a[i++] = '<span class="yo_options"><img title="Click to share selected results to your Google Docs account" alt="Click to share selected results to your Google Docs account" src="'+getYoProp('server')+'/yolinklite/images/transgdocsicon311.png" style="cursor:pointer;" ';
            a[i++] = 'onmouseout="img_mouseover(this);" onmouseover="img_mouseover(this);" onclick="yolink.cloud.Widget.doGDocs();"/>';
            a[i++] = '</span>';
        }

        if (PopOver.options.trash)
        {
            a[i++] = '<span class="yo_options"><img title="Click to remove selected results" alt="Click to remove selected results" src="'+getYoProp('server')+'/yolinklite/images/trashall311.png" style="cursor:pointer;" ';
            a[i++] = 'onmouseout="img_mouseover(this);" onmouseover="img_mouseover(this);" onclick="yolink.cloud.Widget.doTrash();"/>';
            a[i++] = '</span>';
        }

        $tigr('#yolink_popover_options').html(a.join(''));
    },
    renderResults: function(results, url)
    {
        var po = PopOver;
        var anchor = po.anchorMap[url];
        anchor.el.append(results);
        this.popoverContainer.show();
    },

    /**
     * A toggle function to show an hide the popover
     * @return void: The side effect is if the popover is in the off state, it will turn on and vice versa
    */
    showHideToggle : function()
    {
        if($tigr('#popover_hide_link'))
        {
            if(this.popoverContainer.css('display') == 'none')
            {
                $tigr('#popover_hide_link').text('Hide Results');
                this.popoverContainer.css({'display'   : 'block'});
            }
            else
            {
                $tigr('#popover_hide_link').text('Show Results');
                this.popoverContainer.css({'display'   : 'none'});
            }
        }
    },

    /**
     * Used to display the popover.
     * @return void: The side effect is This will set the display the popover
    */
    show : function()
    {
        this._makeDraggable();
        this.popoverContainer.css({'display'   : 'block'});
    },

    onResize: function()
    {
        //get window height
        var winHeight  = $tigr(window).height();

        this.popoverContainer.css({'height' : (Math.floor(winHeight) - 60) + 'px'});
        this.resultsContainer.css({'height' : (this.popoverContainer.height() - 60) + 'px'});
    },

    createMap: function(link)
    {
        var po = PopOver;
        var el = $tigr(document.createElement('li') );
        var resultsDiv = $tigr(document.createElement('div') );
        el.append('<div class="popover_results_top"></div>');
        el.append('<span class="titleLink">'+link.title+'</span>');
        el.append(resultsDiv);
        el.append('<div class="popover_results_bot"></div>');

        po.resultsContainer.append(el);
        po.anchorMap[link.url] = {'title': link.title, 'url': link.url, 'el':resultsDiv,'li':el};
    },

    cull : function(link)
    {
        var el = PopOver.anchorMap[link];
        if( el &&
            el.li )
        {
            $tigr(el.li).remove();
        }
    },

    /*
     * Used to return the number of available results that have not been culled yet. 
     * Culled results mean there is no hit, so the el.li of the containing results is removed from view.
     *
    */ 
    numOfResults : function()
    {
        var results = $tigr(this.resultsContainer).children();
        if( results )
        {
            return results.size();
        }
    },

    _makeDraggable : function()
    {
        if( !PopOver.draggable )
        {
            var pc = PopOver.popoverContainer;

            if( pc.draggable )
            {
                //E3905:prevent dragable beyond the document
                //------------------------------------------
                pc.draggable({ handle: '#yolink_popover_container_title', containment: 'document'});
                PopOver.draggable = true;
            }
        }
    }
};
if (!yolink) var yolink = {};
if (!yolink.cloud) yolink.cloud = {};

yolink.cloud.Facebook =
{
    addOpenGraphResult : function( facebook, sb, index, url, options )
    {
        if( facebook &&
            facebook.property )
        {
            var tb      = yolink.cloud.Widget;
            var ogimage = null;
            var ogurl   = null;
            var match   = false;
            var always  = options.always;

            for( var i = 0 ; i < facebook.property.length ; ++i )
            {
                var property = facebook.property[ i ];
                var name     = property.name;
                if( name == 'og:image' )
                {
                    ogimage = property.value;
                }
                else
                if( name == 'og:url' )
                {
                    ogurl   = property.value;
                }

                match        = match || property.matched == 'true';
            }

            if( always ||
                match )
            {
                sb.append( '<tr id="fb_' + index + '">' );
                sb.append( '<td></td><td><div class="yo_fbresult"><table cellpadding="2" cellspacing="2" border="0"><tr>' );
                sb.append( '<td align="center" valign="top" width="40" style="padding: 10px; border-top : 0px;">' );

                if( ogimage )
                {
                    if( ogurl )
                    {
                        sb.append( '<a href="' );
                        sb.append( ogurl );
                        sb.append( '">' );
                    }

                    sb.append( '<img src="' );
                    sb.append( ogimage );
                    sb.append( '" alt="Facebook Open Graph" title="Facebook Open Graph" width="48" height="48"/>' );

                    if( ogurl )
                    {
                        sb.append( '</a>')
                    }

                }
                else
                {
                    sb.append( '<img src="'+getYoProp('server')+'/yolinklite/images/facebook_logo.png" alt="Facebook Open Graph" title="Facebook Open Graph" width="48" height="48"/>' );
                }

                sb.append( '</td><td align="left" style="padding: 10px; border-top : 0px;"><span class="yo_fbtitle">Facebook Open Graph Match</span><br><iframe src="http://www.facebook.com/widgets/like.php?href=' );
                sb.append( encodeURIComponent( ogurl ? ogurl : url ) );
                sb.append( '&layout=standard&show_faces=false&width=200&height=70&action=like&colorscheme=light" scrolling="no" frameborder="0" style="border:none; overflow: hidden; width:200px; height:70px; padding: 10px;" allowTransparency="true"></iframe><br>' );

                for( var i = 0 ; i < facebook.property.length ; ++i )
                {
                    var property = facebook.property[ i ];
                    var name     = property.name;
                    if( name != 'og:image' &&
                        name != 'og:url' )
                    {
                        sb.append( '<b>' );
                        yolink.cloud.Facebook._formatPropertyName( sb, property.name );
                        sb.append( "</b>: " );
                        sb.append( property.value );
                        sb.append( '<br>' );
                    }
                }

                sb.append( '</td></tr></table></div><br></td></tr>' );
            }
        }
    },

    _formatPropertyName : function(sb,str)
    {
        if( str.length > 3 )
        {
            // Upper Case first letter.
            // ------------------------
            sb.append( str.charAt( 3 ).toUpperCase() );

            for( var i = 4 ; i < str.length ; ++i )
            {
                var next = str.charAt( i );
                switch( next )
                {
                    case '_':
                    case '-':
                    case ' ':
                        sb.append( ' ' );
                        if( ++i < str.length )
                        {
                            sb.append( str.charAt( i ).toUpperCase() );
                        }
                        break;

                    default:
                        sb.append( next );
                        break;
                }
            }
        }
    }
}/*****************************************************************************************
 * TigerLogic Corp.
 *
 * Copyright (c) Raining Data Corp. All Rights Reserved.
 *
 * This software is confidential and proprietary information belonging to
 * TigerLogic. It is the property of TigerLogic. and is protected
 * under the Copyright Laws of the United States of America.  No part of this
 * software may be copied or used in any form without the prior
 * written permission of TigerLogic Corp.
 *
 *****************************************************************************************/

if (!yolink) var yolink = {};
if (!yolink.cloud) yolink.cloud = {};

yolink.cloud.GoogleCustomSearch =
{
    options : null,
    count : 0,
    isLocal : false,

    initialize : function(args)
    {
        var cgcs = yolink.cloud.GoogleCustomSearch;

        cgcs.options = args;
        tigr.api.APIKey.setKey(args.apikey);
        cgcs.isLocal = document.domain == 'cloud.yolink.com';

        // Defaults.
        // ---------
        cgcs.options.maxResults = cgcs.options.maxResults || 4;
        cgcs.options.showHide = cgcs.options.showHide ? args.showHide : true;
        cgcs.options.apikey = cgcs.options.apikey | '';
        cgcs.options.preview = cgcs.options.preview | false;

        this.initializeCSS();
        this.initializeCSSIE();
        if(cgcs.options.noConflict)
        {
		 $tigr = jQuery.noConflict();
	}	 
        
    },

// Callback to load CSS (dependant on ajax.js).
    initializeCSS : function()
    {
        $tigr.getCSS('http://cloud.yolink.com/yolinklite/css/embed.css');
    },
    initializeCSSIE : function()
    {
        var cgcs = yolink.cloud.GoogleCustomSearch;

        if (cgcs.options.preview && !tigr.util.IESupportsModernCSS(document))
        {
            $tigr.getCSS('http://cloud.yolink.com/yolinklite/css/preview-ie.css');
        }
    },
    doSearch : function(result, clear)
    {
        var cgcs = yolink.cloud.GoogleCustomSearch;
        if (cgcs.options.preview)
        {
            Preview.initialize();
        }
        if (clear)
        {
            cgcs.clear();

            cgcs.count = 0;
        }

	/*
		commented for bug 3514
		we need to refresh links html 
		everytime
	*/
        //if (!cgcs.results)
        //{
            //cgcs.results = cgcs.getResults();
        //}
        
        cgcs.results = cgcs.getResults();
	

        if (result)
        {
            var typeOf = typeof(result);
            if (typeOf == 'integer')
            {
                cgcs.doSearchItem(result, cgcs.results[result]);
            }
        }
        else
        {
            $tigr(cgcs.results).each(
                    function(index, value)
                    {
                        cgcs.doSearchItem(index, value);
                        ++cgcs.count;
                    });
        }
    },

    showHideResult : function(index)
    {
        if (yolink.cloud.GoogleCustomSearch.options.showHide)
        {
            var form = $tigr('#yo_f_' + index);
            var a = $tigr('#yo_fa_' + index);
            var show = $tigr(form).css('display') == 'none';
            if (show)
            {
                $tigr(a).text('Hide yolink Results');
                form.fadeIn('slow');
            }
            else
            {
                $tigr(a).text('Show yolink Results');
                form.fadeOut('slow');
            }
        }
    },

    showResult : function(index)
    {
        $tigr('#yo_f_' + index).fadeIn('fast');
        $tigr('#yo_ah_' + index).fadeOut('slow');
        $tigr('#yo_ht_' + index).fadeIn('slow');
    },

    selectAll : function(selected, index)
    {
        if (index)
        {
            var form = $tigr('#yo_f_' + index);
            if (form)
            {
                $tigr('input[type="checkbox"]', form).checked = selected;
            }
        }
        else
        {
            $tigr('.yo_cb').checked = selected;
        }
    },

    clear : function(index)
    {
        if (index)
        {
            $tigr('#yo_div_' + index).remove();
        }
        else
        {
            var cgcs = yolink.cloud.GoogleCustomSearch;
            for (var i = 0; i < cgcs.count; ++i)
            {
                $tigr('#yo_div_' + i).remove();
            }
        }
    },

// ------------------------------------------------------------------------

    makeSearchResult : function(index, url, results, contentType)
    {
        var cgcs = yolink.cloud.GoogleCustomSearch;
        var div = document.createElement('div');
        var show = document.createElement('a');
        var rdiv = document.createElement('div');
        var form = document.createElement('form');
        var table = document.createElement('table');
        var tbody = document.createElement('tbody');
        var htable = null;
        var htbody = null;
        var ctable = table;
        var ctbody = tbody;
        var maxMore = false;

        div.id = 'yo_div_' + index;
        $tigr(div).css('class', 'yo_div');

        form.id = 'yo_f_' + index;
        form.action = '';
        $tigr(form).css("class", 'yo_f');
        rdiv.id = 'yo_r_' + index;
        $tigr(rdiv).css("class", 'yo_r');
        rdiv.appendChild(form);

        show.id = 'yo_fa_' + index;
        $tigr(show).attr('href', 'javascript:yolink.cloud.GoogleCustomSearch.showHideResult(' + index + ');');
        $tigr(show).text('Hide yolink Results');

        if (cgcs.options.showHide)
        {
            div.appendChild(show);
        }

        table.appendChild(tbody);
        div.appendChild(rdiv);

        form.appendChild(table);

        for (var i = 0; i < results.length; ++i)
        {
            if (!maxMore &&
                i >= yolink.cloud.GoogleCustomSearch.options.maxResults)
            {
                maxMore = true;

                var a = document.createElement('a');

                a.id = 'yo_ah_' + index;
                a.href = 'javascript: yolink.cloud.GoogleCustomSearch.showResult(' + index + ');';
                $tigr(a).text('More Results Available');

                htable = document.createElement('table');
                htbody = document.createElement('tbody');
                ctable = htable;
                ctbody = htbody;

                $tigr(htable).css("class", 'yo_mr');
                htable.id = 'yo_ht_' + index;
                htable.style.display = 'none';

                htable.appendChild(htbody);
                form.appendChild(a);
                form.appendChild(ctable);
            }

            var value = results[ i ];
            var tr = document.createElement('tr');
            var td1 = document.createElement('td');
            var td2 = document.createElement('td');
            var input = document.createElement('input');
            var action = document.createElement('a');

            action.name ="chunk-link";
            action.resultindex= index;
            action.id= form.id + '_yo_preview_' + i;
            
            input.id = form.id + '_' + i;
            input.type = 'checkbox';
            $tigr(input).css("class", 'yo_cb');
            input.checked = false;
            input.location = value.location;
            input.virtual = value.virtual;

            $tigr(td1).attr('valign', 'top');
            // align the bullets to the top but leave the checkboxes in the default center position
            // ---------------
            if (!cgcs.options.checkboxes)
            {
                td1.style.verticalAlign='top';
            }
            td1.align = 'center';

            $tigr(td1).css("class", 'yo_fc');
            td2.id = 'yo_fd_' + index + '_' + i;

            // $tigr(td2).html('<a class="yo_fd" href="javascript:void">' + value.value + '</a>');
            $tigr(action).attr('class', 'yo_fd yo_preview');
            // Enable preview.
            // ---------------
            if (cgcs.options.preview)
            {
                var purl = url;
                if (cgcs.options.forPreviewURL)
                {
                    purl = cgcs.options.forPreviewURL(url);
                }

            Preview.registerPreviewAction(action, purl, value.id, value.virtual, index, (contentType || 'text/html'));
            }
            $tigr(action).append(value.value);
            td2.appendChild(action);


            if (cgcs.options.checkboxes)
            {
                td1.appendChild(input);
            }
            else
            {
                $tigr(td1).html('&bull;');
            }

            tr.appendChild(td1);
            tr.appendChild(td2);
            ctbody.appendChild(tr);
        }

        return div;
    },

    doSearchItem : function(index, result)
    {
        var cgcs     = yolink.cloud.GoogleCustomSearch;
        var anchor   = cgcs.getAnchor(result);
        var keywords = cgcs.getKeywords();
        var target   = cgcs.getURL(result);

        if (target)
        {
            var local    = cgcs.isLocal;
            var resolved = cgcs.resolve(target);
            var url      = cgcs.makeSearchURL(target, keywords, local);
            var callback = function(data)
            {
                var results = data.rs.r;
                if (results)
                {
                    try
                    {
                        var html = cgcs.makeSearchResult(index, resolved, data.rs.r, data.rs.type);

                        $tigr(anchor).append(html);
                    }
                    catch(e)
                    {
                        alert(' in side doSearchItem(): ERROR: ' + e);
                    }
                }
            }

            try
            {
                if (local)
                {
                    $tigr.ajax(
                    {
                        url : url,
                        async : true,
                        cached : false,
                        type : 'GET',
                        dataType : 'json',
                        success : callback
                    });
                }
                else
                {
                    $tigr.get(url, null, callback, 'jsonp');
                }
            }
            catch(e)
            {
                alert('doSearchItem: error: ' + e);
            }
        }
    },

    makeSearchURL : function(url, keywords, local)
    {
        var cgcs = yolink.cloud.GoogleCustomSearch;
        var result = 'http://api.yolink.com';

        result += '/yolinklite/search-page?ak=';
        result += encodeURIComponent(tigr.api.APIKey.getKey());
        result += '&q=';
        result += encodeURIComponent(keywords);
        result += '&u=';
        result += encodeURIComponent(cgcs.resolve(url));
        result += '&o=';
        result += ( local ? 'json' : 'jsonp' );
        result += '&oe=UTF-8';

        return result;
    },

    resolve : function(url)
    {
        if (url.indexOf(':') < 0)
        {
            var base = yolink.cloud.GoogleCustomSearch.options.base;
            if (!base)
            {
                base = document.location.href;
            }

            if (url[ 0 ] == '/')
            {
                url = base.substring(0, base.indexOf('/', 8)) + url;
            }
            else
            {
                url = base.substring(0, base.lastIndexOf('/') + 1) + url;
            }
        }

        return url;
    },

    exec : function(src, root)
    {
        if (src)
        {
            try
            {
                switch (typeof(src))
                        {
                    case 'string':
                        return $tigr(src, root);

                    case 'function':
                        return src(root);
                }
            }
            catch(e)
            {
                alert("exec error: " + e);
            }

            return null;
        }
        else
        {
            return root;
        }
    },

    getKeywords : function()
    {
        return $tigr('.gsc-input')[1].value;
    },

    getResults : function()
    {
        return $tigr('.gsc-result');
    },

    getURL : function(result)
    {
        return $tigr('a.gs-title', result).attr('href');
    },

    getAnchor : function(result)
    {
        return result;
    },

    _preview : function(event)
    {
    },

    _trySearch : function()
    {
        var cgcs = yolink.cloud.GoogleCustomSearch;
        var keywords = cgcs.getKeywords();

        if (keywords &&
            keywords.length > 0)
        {
            //cgcs.log('Enter _trySearch');

            try
            {
                var check = $tigr('.gsc-result')[ 0 ]
                if (check &&
                    check != cgcs._lastCheck)
                {
                    //cgcs.log('GO!');
                    cgcs._lastCheck = check;
                    cgcs.doSearch();
                }//don't need this since we have handle using setSearchCompleteCallback
                /*else
                {
                    cgcs.log( 'waiting...' );
                    setTimeout( cgcs._trySearch, 400 );
                }*/
            }
            catch(e)
            {
                alert("try: " + e);
            }
        }
    },

    log : function(msg)
    {
        $tigr('#yoconsole').append('<p>' + msg + '</p>');
    },
    
    appendEnhancedYolinkImg: function()
    {
      if ($tigr.browser.msie)
        {
        	$tigr('.gsc-branding').append($tigr('<tr><td class=""></td><td  vertical-align="top" colspan=2  style="text-align:right;float: right;margin-right: 890px;"><img src="http://cloud.yolink.com/yolinklite/images/yolink_enhanced_inline_alt.png"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr>'));
        }else{
    
        	$tigr('.gsc-branding').append('<tr><td class="gsc-branding-user-defined"></td><td class="gsc-branding-img" vertical-align="top" colspan=2 align="right"><img src="http://cloud.yolink.com/yolinklite/images/yolink_enhanced_inline_alt.png">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr>');
        }

    }    
};

// Create a new .getCSS function analogous to the .getScript function.
(function($tigr)
{
    $tigr.getCSS = function(url, media)
    {
        $tigr(document.createElement('link')).attr({
            href : url,
            media: media || 'screen',
            type : 'text/css',
            rel  : 'stylesheet'
        }).appendTo('head');
    }
})($tigr);

$tigr(document).ready(
        function()
        {
            $tigr(document.body).append('<div id="yoconsole"></div>');
        })

$tigr(window).load(
        function()
        {
            
            if ($tigr.browser.msie)
            {
                setTimeout( yolink.cloud.GoogleCustomSearch.appendEnhancedYolinkImg, 400 );
            }else{
            	yolink.cloud.GoogleCustomSearch.appendEnhancedYolinkImg();
            }

            //$tigr('input.gsc-search-button').click( function(e){ yolink.cloud.GoogleCustomSearch._trySearch() } );
        });

