/* Note to site visitors viewing this file: this is not the typical means of setting up the code. 
See the download file for demonstration of implementation. */

dw_Util.inArray = function(val, ar) {
    for (var i=0; ar[i]; i++) {
        if ( ar[i] == val ) {
            return true;
        }
    }
    return false;
}

// object detection from http://benalman.com/projects/jquery-hashchange-plugin/
dw_Util.supportsHashchange = function() {
    return 'onhashchange' in window && ( !document.documentMode || document.documentMode > 7 );
}


dw_TipDemos = {
    request: null,
    current: null,
    
    setupLinks: function(id) {
        if ( dw_Util.supportsHashchange() ) { return; } // use onhashchange instead of function call onlick
        var links = document.getElementById(id).getElementsByTagName('a');
        for (var i=0; links[i]; i++) {
            if (links[i].className.indexOf('tipsdemo_') !== -1) {
                links[i].onclick = dw_TipDemos.getProps;
            }
        }
    },
    
    doOnHashChange: function() {
        var _this = dw_TipDemos;
        var demo, hash = location.hash.length > 1? location.hash.slice(1): '';
        if ( hash && dw_Util.inArray(hash, DEMOS_AR) ) {
            demo = hash;
        } else if ( _this.current && !location.search ) {
            demo = _this.current;
        } else {
            demo = STARTING_DEMO;
        }
        _this.getProps(demo);
    },
    
    getProps: function (demo) {
        var _this = dw_TipDemos;
        if ( typeof demo != 'string' && this.className ) { // link clicked
            demo = this.className.slice(9); // 'tipsdemo_' length
        }
        // encodeURIComponent
        var url = 'demos/data.php?demo=' + demo + '&i=' + new Date().getTime();
        if ( _this.request ) {
            _this.request.abort();
        }
        var req = _this.request = dw_XHR.makeRequest(url, _this.callback );
        if (req) {
            dw_Tooltip.defaultProps = {}; dw_Tooltip.content_vars = {};
            _this.toggleNotes(demo);
        } else {
            alert('The tooltip demonstration requires a browser supporting ajax.');
        }
        return false; // may be link onclick
    },
    
    toggleNotes: function (id) {
        if (this.current) {
            document.getElementById(this.current).style.display = 'none';
        }
        var el = document.getElementById(id);
        if ( el ) { // may not exist 
            el.style.display = 'block';
            this.current = id;
        }
    },
    
    handleData: function () {
        var _this = dw_TipDemos;
        var req = _this.request;
        var str = req.responseText;
        var data = str.split('||');
        //dw_Tooltip.defaultProps = eval( '(' + data[0] + ')' );
        dw_Tooltip.defaultProps = JSON.parse(data[0], _this.reviver );
        dw_Tooltip.content_vars = JSON.parse(data[1], _this.reviver );
        dw_Tooltip.init(); // after getting props
    },
    
    reviver: function(key, value) {
        if ( key == 'wrapFn' || key == 'positionFn' ) {
            value = eval(value);
        }
        return value;
    },
    
    handleFailure: function () {
        alert('Unable to retrieve data for the demo');
    }
    
}

dw_TipDemos.callback = {
    success: dw_TipDemos.handleData,
    failure: dw_TipDemos.handleFailure
}

var dw_Util; if (!dw_Util) dw_Util = {};

dw_Util.writeStyleRule = function(rule, bScreenOnly) {
    var media = (bScreenOnly != false)? ' media="screen">': '>';
    document.write( '\n<style type="text/css"' + media + rule + '</style>');
}


/*************************************************************************
    This code is from Dynamic Web Coding at dyn-web.com
    Copyright 2010 by Sharon Paine 
    See Terms of Use at www.dyn-web.com/business/terms.php
    regarding conditions under which you may use this code.
    This notice must be retained in the code as is!
*************************************************************************/

// ajax_tip.js version date: July 2010
// for use with dw_tooltips.js to retrieve content via ajax

dw_Tooltip.initAjaxRequest = function (id) {
    dw_Tooltip.Ajax.init(id);
}

dw_Tooltip.Ajax = {
    request: null, reqTimer: 0, lastRequest: 0, // avoid repeated rapid requests
    // need longer delay for ie6 ? (can crash on old slow pc's)
    reqDelay: (window.ActiveXObject && !window.XMLHttpRequest)? 1000: 500,
    pendingReq: false, respRecd: false,
    
    init: function (id) {
        var obj = dw_Tooltip.content_vars[id];
        // to display in tooltip while waiting for response
        var msg = this.waitMsg? this.waitMsg: 'Retrieving info ...';
        obj['content'] = msg;
        var queryStr = obj.params? dw_XHR.encodeVars(obj.params): '';
        this.pendingReq = true;
        
        var ts = new Date().getTime(); var dif = ts - this.lastReq;
        if ( this.lastReq > 0 && dif < this.reqDelay ) { // institute delay 
            this.reqTimer = setTimeout( function() { dw_Tooltip.Ajax.send(queryStr, id); }, this.reqDelay - dif);
        } else {
            dw_Tooltip.Ajax.send( queryStr, id );
        }
    },
    
    send: function (reqData, id) {
        var obj = dw_Tooltip.content_vars[id];
        // page that performs the query, can specify in dw_Tooltip.Ajax.reqURL or 
        // each could have separate url specified in content_vars url prop
        var url = obj['url']? obj['url']: this.reqURL;
        
        // hold timestamp and use to control rate of requests
        var ts = this.lastReq = new Date().getTime();
        url += '?' + reqData + '&rnd=' + ts; 
        
        var callback = { // set success and failure handlers
            success: function(req) { dw_Tooltip.Ajax.handleResponse(req, id); },
            failure: this.handleFailure
        }
        
        this.request = dw_XHR.makeRequest(url, callback );
    },
    
    handleResponse: function (req, id) {
        // if responseText is tooltip content 
        var msg = req.responseText;
        var _this = dw_Tooltip.Ajax;
        
        // if json or xml result, could  parse here 
        // could use id to save result in content_vars and set 'static'
        
        // json ...       
        if ( typeof JSON != 'undefined' && JSON.parse ) {
            try {
                var o = JSON.parse(msg);
                if ( typeof o == 'object' ) {
                    var obj = dw_Tooltip.content_vars[id];
                    for (var i in o) {
                        obj[i] = o[i];
                    }
                    msg = obj;
                }
            } catch (err) {
            }
        }
        
        _this.respRecd = true;
        _this.writeTip(msg, true); dw_Tooltip.adjust();
        _this.request = null; // dereference when done
    },
    
    handleFailure: function () {
        // message on failure? 
        var msg = 'Data unavailable';
        dw_Tooltip.Ajax.respRecd = true;
        dw_Tooltip.Ajax.writeTip(msg, true);
        dw_Tooltip.adjust();
    },
    
    writeTip: function(msg, bReqFlag) {
        var _this = dw_Tooltip.Ajax;
        if ( _this.pendingReq && _this.respRecd && !bReqFlag ) return;
        msg = dw_Tooltip.wrapFn(msg); dw_Tooltip.tip.innerHTML = msg;
    },
    
    resetRequest: function () {
        var _this = dw_Tooltip.Ajax;
        if ( _this.request ) { _this.request.abort(); }
        _this.respRecd = false; _this.pendingReq = false;
        if ( _this.reqTimer ) { clearTimeout( _this.reqTimer ); _this.reqTimer = 0; }
    }
    
}

dw_Tooltip.writeTip = dw_Tooltip.Ajax.writeTip;
dw_Tooltip.resetRequest = dw_Tooltip.Ajax.resetRequest;



/////////////////////////////////////////////////////////////////////
// customized for ajax demo
dw_Tooltip.wrapImageOverText = function(obj) {
    var str = ''; if (!obj) return str; 
    if ( !obj['img'] ) { // before response received
        str = obj['content']? obj['content']: obj; // obj may be string (msg)
        return str;
    }
    dw_Util.getImage( obj['img'] );
    var caption = obj['caption'] || '';
    str = '<div class="img"><img src="' + obj['img'] + '" /></div><div class="txt">' + obj['txt'] + '</div>';
    if ( this.sticky && this.defaultProps['showCloseBox'] ) {
        str = dw_Tooltip.wrapSticky(str, caption );
    } else {
        if (caption) { str = '<div class="caption">' + obj['caption']  + '</div>' + str; }
    }
    if ( obj['w'] ) this.setTipWidth( obj['w'] );
    return str;
}
//
/////////////////////////////////////////////////////////////////////
