// popupim_src.js
// Should be packed at http://dean.edwards.name/packer/
// and saved as popupim.js
var CamSenseIM = (function() {
    var cf = {
        // Full URL to this promo tool
        selfURL  : "http://www.camsense.com/promo/popupim/",
        reqURL : "http://www.ccnwebcams.com/ns/popupim.rss",
        // DIVs name space
        NS : 'camsenseIM',
        // IM height
        height : 115,
        // IM width
        width : 200,
        // IM color schemes
        textColor  : ['471313','233443','543709','074b19','1f214c','404040','fff','163817','232a23','4f0707','460734','353535'],
        borderColor: ['b46060','4f7ba6','ad6900','4a8514','282a54','515151','000','1f4020','232a23','4f0707','7b0158','a3a3a3'],
        wrpName : function () {
            return this.NS +'Box';
        },
        bgfName : function () {
            return this.NS +'BgFrame';
        },
        cntName : function () {
            return this.NS +'Content';
        },
        bgImg: new Image(),
        picsURL    : '',
        siteURL    : '',
        pageURL    : '',
        page       : '',
        profiles   : [],
        isVisible  : false
    };
    // updating hostname for devel
    if ( /^camsense\.devel\.iss\.lv$/i.test( location.hostname ) ) {
        cf.selfURL  = cf.selfURL.replace(/www\.camsense\.com/i, 'camsense.devel.iss.lv');
        cf.reqURL   = cf.reqURL.replace(/www\.ccnwebcams\.com/i, 'www.ccnwebcams.com.wl.myccn.org');
    }
    // Append new DOM element with properties
    function addElm(elm,props,where) {
        var where = where||'head';
        var p   = getEbtn(where);
        var elm = document.createElement(elm);
        for (var i in props) elm[i] = props[i];
        p.appendChild(elm);
        return elm;
    };
    // GetElementbyID
    function getEbid(elmID) {
        return document.getElementById(elmID) || false;
    };
    // GetElementByTagName
    function getEbtn(elm,loc,index) {
        var loc   = loc||document;
        var index = index||0;
        return loc.getElementsByTagName(elm)[index] || false;
    };
    // set auto reload timer
    function setAutoReloadTimer( clear ) {
        if ( cf.autoReload ) {
            clearTimeout( cf.autoReload );
            cf.autoReload = setTimeout(function() {
                if (cf.profiles.length) showIM();
                else if (cf.autoReload) clearTimeout(cf.autoReload);
            }, cf.autoDelay);
        }
    };
    // Hide nicely im and request next profile
    function showIM(isClick) {
        if (cf.profiles.length==0) return;

        if ( isClick ) {
            showProfile( isClick );
        }
        else {
            var ht = 0;
            var sm  = setInterval(function () {
                ht += 12;
                getEbid(cf.cntName()).style.top = getEbid(cf.bgfName()).style.top = ((ht < cf.height ) ? ht:cf.height)+'px';
                if ( ht >= cf.height ) {
                    clearInterval(sm);
                    cf.isVisible = false;
                    showProfile( isClick );
                }
            }, 1);
        }
    };
    // Change picture and CH name, reset timer and show box if hidden
    function showProfile(isClick) {
        var profile = cf.profiles.shift();

        cf.pageURL = cf.siteURL + cf.page.replace('#SNAME#', profile.sn);

        for ( var i = 0; i < 5; i++ ) {
            var a = getEbtn('a',getEbid(cf.cntName()),i);
            if ( !a ) break;
            a.href = cf.pageURL;
        }

        var img = new Image();

        img.onload = function() {
            this.onload = {};
            getEbtn('img',getEbid(cf.cntName())).src = this.src;
            getEbtn('big',getEbid(cf.cntName())).innerHTML = profile.sn;
            // show box if not visible
            if ( !cf.isVisible ) {
                cf.isVisible = true;
                getEbid(cf.wrpName()).style.display = 'block';
                var ht = cf.height;
                var sm  = setInterval(function () {
                    ht -= 3;
                    getEbid(cf.cntName()).style.top = getEbid(cf.bgfName()).style.top = ((ht > 0) ? ht : 0)+'px';
                    if ( ht <= 0 ) {
                        clearInterval(sm);
                        setAutoReloadTimer();
                    }
                },cf.showSpeed);
            }
        };

        img.src = cf.picsURL + profile.pic +'?r='+ (new Date()).getTime();

        if ( isClick ) {
            setAutoReloadTimer();
        }
    };
    function createIM() {
        // quit if this function has already been called
        if (arguments.callee.done) return;
        // flag this function so we don't do the same thing twice
        arguments.callee.done = true;

        // Add Camsense IM stylesheet
        addElm('link',{
            type: 'text/css',
            rel:  'stylesheet',
            href: cf.selfURL +'style.css'
        },'head');

        var div = addElm('div',{id:cf.wrpName()},'body');
        div.style.display = 'none';
        div.style.height  = cf.height+'px';
        div.style.width   = cf.width+'px';
        // detect IE in quirks mode
        var fixIE = ( '\v'=='v' && (!document.compatMode || document.compatMode != 'CSS1Compat') );
        // iFrame to get IM above Flash (if any)
        var imcont = '<iframe id="'+cf.bgfName()+'" frameborder="0" scrolling="no" style="height:'+cf.height+'px;left:0;position:absolute;top:'+cf.height+'px;width:'+cf.width+'px;z-index:14999"></iframe>'+
            '<div id="'+cf.cntName()+'" style="border:1px solid #'+cf.borderColor[cf.typeID]+';background:url('+ cf.bgImg.src +') no-repeat;color:#'+cf.textColor[cf.typeID]+';height:'+(cf.height-(fixIE?0:2))+'px;left:0;top:'+cf.height+'px;padding:0 6px;position:absolute;width:'+(cf.width-(fixIE?0:14))+'px;z-index:15000">'+
                '<h1><a href="#closeIM" class="closeIM" title="Close"><span>Close</span></a> You\'ve got a message!</h1>'+
                '<p><a href="#" style="color:#'+cf.textColor[cf.typeID]+'" rel="external"><img src="about:blank" height="45" width="60" alt="" style="border:1px solid #'+cf.borderColor[cf.typeID]+'">'+
                '<big></big><br>Is online now</a></p>'+
            '<ul>';

        if ( cf.typeID <= 3 ) {
                imcont += '<li><a href="#" style="color:#'+cf.textColor[cf.typeID]+'" title="Join her" rel="external">Join her</a></li>'+
                '<li id="nimg"><a href="#" style="color:#'+cf.textColor[cf.typeID]+'" title="Next" rel="next">Next</a></li>';
        }
        else if ( cf.typeID > 3 && cf.typeID < 8 ) {
            imcont += '<li id="center"><a href="#" style="color:#'+cf.textColor[cf.typeID]+'" title="Chat with her now!" rel="external">Chat with her now!</a></li>';
        }
        else {
            imcont += '<li id="button"><a href="#" style="color:#'+cf.textColor[cf.typeID]+'" title="Join her" rel="external"><span>Join her</span></a></li>';
        }

        imcont += '</ul></div>';
        div.innerHTML = imcont;
        // Set color for H1 according to selected IM
        getEbtn('h1',getEbid(cf.cntName())).style.color = '#'+cf.textColor[cf.typeID];
        // Attach Div onclick events
        getEbid(cf.cntName()).onclick = function (evt) {
            evt = evt || window.event;
            var tg = evt.target || evt.srcElement;
            if (tg.nodeType == 3) // defeat Safari bug
                tg = tg.parentNode;
            if (tg.parentNode.rel == 'external') {
                tg.parentNode.target = cf.newWin ? '_blank' : '_top';
                return true;
            }
            else if (tg.rel == 'external') {
                tg.target = cf.newWin ? '_blank' : '_top';
                return true;
            }
            else if (tg.className == 'closeIM') {
                getEbid(cf.wrpName()).style.display = 'none';
                // If autoreload is working, stop it
                if (cf.autoReload) clearTimeout(cf.autoReload);
                return false;
            }
            else if (tg.rel == 'next') {
                // While there are images display it, else redirect to site
                if (cf.profiles.length) {
                    showIM(true);
                    return false;
                }

                tg.target = cf.newWin ? '_blank' : '_top';
                return true;
            }
        };
    };
    // make request by including remote js file
    function requestProfiles() {
        addElm('script',{
            type: 'text/javascript',
            src:  cf.reqURL + '?siteID='+ cf.siteID
                            + '&catID='+ cf.catID
                            + '&amount='+ cf.chCount
                            + '&ts='+ (new Date()).getTime()
        });
    };
    // Public members
    return {
        feed: function (json) {
            if (!('profiles' in json)) return false;
            cf.picsURL  = json.picsURL;
            cf.siteURL  = json.siteURL;
            cf.profiles = json.profiles;

            if ( ( 'parseTime' in json ) && window.console ) {
                console.debug( 'Request Time: '+ json.parseTime );
            }

            showIM();
        },
        init : function (o) {
            try {
                // Check if required argument is passed
                var check = ['typeID', 'siteID', 'catID', 'page'];

                for ( var i = 0; i < check.length; i++ ) {
                    if ( !( check[ i ] in o ) ) {
                        throw new Error('CamsenseIM - Missing or incorrect parameters');
                    }
                }
            } catch ( e ) {
                alert( e.name +': '+ e.message );
                return false;
            }

            // selected IM No
            cf.typeID   = (o.typeID >= 1 && o.typeID <= 12) ? parseInt( o.typeID ) - 1 : 0;
            // site to send traffic to
            cf.siteID   = parseInt( o.siteID );
            // category to select chathosts
            cf.catID    = parseInt( o.catID );
            // Page for landing
            cf.page     = decodeURIComponent( o.page );
            // Amount of chathosts to show
            cf.chCount  = parseInt( o.chCount ) || 4;
            // Messenger slide in speed (msec)
            cf.showSpeed = parseInt( o.showSpeed ) || 15;
            // Delay before start to show (sec)
            cf.showDelay = ('showDelay' in o) ? parseFloat( o.showDelay ) : 1;
            // Automatically reload image
            cf.autoReload = ('autoReload' in o) ? o.autoReload : true;
            // Delay for autoreload
            cf.autoDelay= ('autoDelay' in o) ? parseFloat( o.autoDelay ) : 10;
            // Links will be opened in new window
            cf.newWin   = ('newWin' in o) ? o.newWin : true;

            cf.showDelay *= 1000;
            cf.autoDelay *= 1000;

            cf.bgImg.src = cf.selfURL +'img/bg'+ (cf.typeID+1) +'.png';

            var prevOnload = window.onload;
            window.onload = function() {
                if ( typeof( prevOnload ) == 'function') {
                    prevOnload();
                }
            
                createIM();
                window.setTimeout( requestProfiles, cf.showDelay );
            };
        }
    };
})();
