// peelad_src.js
// Should be packed at http://dean.edwards.name/packer/
// and saved as peelad.js

var CamSensePA = (function () {
    var pa = {
        remoteURL:  'http://www.camsense.com/promo/peelads/',
        page:       '',
        type:     '',
        corner:     '',
        namePrefix: 'camsensePA',
        flashFile:  'corner.swf',
        small: {
            img: new Image(),
            css: {height:'100px', width:'100px', position:'absolute', top:0, right:0, left:'',bottom:''}
        },
        large: {
            img: new Image(),
            css: {height:'510px', width:'510px'}
        },
        extCall: 'fscommand', // available values: fscommand (default), geturl, interface (fp8+)
        name: function() {
            var suff = arguments[0] || 'Div';
            return pa.namePrefix + suff;
        },
        flashURL: function() {
            return pa.remoteURL + pa.flashFile;
        }
    };
    // set devel hostname
    // REMOVE FOR LIVE
    if ( /^camsense\.devel\.iss\.lv$/i.test( location.hostname ) ) {
        pa.remoteURL = pa.remoteURL.replace(/www\.camsense\.com/i, 'camsense.devel.iss.lv');
    }

    /* Create and insert FLASH object (simplified swfObject)
     * Documentation http://code.google.com/p/flashreplace/
     */
    var insertFlash = {
        elmToReplace:        null,
        flashIsInstalled:    null,
        defaultFlashVersion: 7,
        replace: function (elmToReplace, src, id, width, height, version, params) {
            this.elmToReplace     = document.getElementById(elmToReplace);
            this.flashIsInstalled = this.checkForFlash(version || this.defaultFlashVersion);
            if (this.elmToReplace && this.flashIsInstalled) {
                var obj = '<object id="'+id+'" ' + ((window.ActiveXObject)? '" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" data="' + src + '"' : '');
                obj += ' width="' + width + '"';
                obj += ' height="' + height + '"';
                obj += '>';
                var param = '<param';
                param += ' name="movie"';
                param += ' value="' + src + '"';
                param += '>';
                param += '';
                var extraParams = '';
                var extraAttributes = '';
                for (var i in params){
                    extraParams += '<param name="' + i + '" value="' + params[i] + '">';
                    extraAttributes += ' ' + i + '="' + params[i] + '"';
                }
                var embed = '<embed name="' + id + '" src="' + src + '" type="application/x-shockwave-flash" width="' + width + '" height="' + height + '"';
                var embedEnd = extraAttributes + '></embed>';
                var objEnd = '</object>';
                this.elmToReplace.innerHTML = obj + param + extraParams + embed + embedEnd + objEnd;
            }
        },
        checkForFlash: function (version) {
            this.flashIsInstalled = false;
            var flash;
            if (window.ActiveXObject) {
                try {
                    flash = new ActiveXObject(("ShockwaveFlash.ShockwaveFlash." + version));
                    this.flashIsInstalled = true;
                }
                catch(e) {
                    // Throws an error if the version isn't available
                }
            }
            else if (navigator.plugins && navigator.mimeTypes.length > 0) {
                flash = navigator.plugins["Shockwave Flash"];
                if (flash ){
                    var flashVersion = navigator.plugins["Shockwave Flash"].description.replace(/.*\s(\d+\.\d+).*/, "$1");
                    if (flashVersion >= version) {
                        this.flashIsInstalled = true;
                    }
                }
            }
            return this.flashIsInstalled;
        }
    };
    // Add CSS
    function addCss(elmID,css) {
        var s = pa.small.css;
        // Set corner location according to choice
        switch (pa.corner) {
            case 'TL': // top left
                s.bottom = '';
                s.left   = 0;
                s.right  = '';
                s.top    = 0;
            break;
            case 'BL': // bottom left
                s.bottom = 0;
                s.left   = 0;
                s.right  = '';
                s.top    = '';
            break;
            case 'BR': // bottom right
                s.bottom = 0;
                s.left   = '';
                s.right  = 0;
                s.top    = '';
            break;
        };
        for (var i in css) {
            elmID.style[i] = css[i];
        }
    };
    // Add DIVs and FLASH element
    function createAd() {
        var ne = document.createElement('div');
        ne.id  = pa.name();
        document.body.appendChild(ne);
        addCss(ne, pa.small.css);
        pa.obj = ne;

        var target = pa.newWin ? '_blank' : '_top';

        insertFlash.replace(pa.name(),pa.flashURL(),pa.name('Flash'),'100%','100%',8,{
            flashvars:        'externalCall=' + pa.extCall
                                    + '&sizeMethod=CamSensePA.setAdSize'
                                    + '&align=' + pa.corner.toLowerCase()
                                    + '&radius=' + pa.radius
                                    + '&big=' + pa.large.img.src
                                    + '&small=' + pa.small.img.src
                                    + '&link=' + encodeURIComponent( pa.page )
                                    + '&linkTarget=' + target,
            menu:             'false',
            wmode:            'transparent',
            allowScriptAccess:'always'
        });
    };
    
    if ( pa.extCall == 'fscommand' ) {
        // Add crap needed for IE to execute DoFSCommand
        document.write('<!--[if IE]>' +
            '<script type="text/javascript" event="FSCommand(command,args)" for="' + pa.name('Flash') + '">' +
                'camsensePAFlash_DoFSCommand(command, args);' +
            '</script><![endif]-->');
    }

    return {
        // If externalCall = interface
        setAdSize: function(size) {
            var css = (size == 'small') ? pa.small.css : pa.large.css;
	        addCss(pa.obj, {height:css.height, width:css.width});

            if (window.opera) { // workaround to make it work properly in Opera
				var f = pa.obj.getElementsByTagName('embed')[0];
                window.setTimeout(function() {
				    f.attributes.width.nodeValue = '100%';
				    f.attributes.height.nodeValue = '100%';
                }, 0);
            }
        },
        // Initialize peel ad creation
        init: function(o) {
            // Check if argument is passed and it is an object
            try {
                // Check if required argument is passed
                if ( !( 'type' in o ) || !( 'page' in o ) ) {
                    throw new Error('CamsensePA - Missing or incorrect parameters');
                }
            } catch (e) {
                alert(e.name+': '+e.message);
                return false;
            }

            // Set values/defaults
            pa.type = o.type.toLowerCase().replace(/\//g,'');
            // Page for landing
            pa.page = decodeURIComponent( o.page );
            // Corner to glue
            pa.corner = (o.corner||'').toUpperCase();
            // Radius ??
            pa.radius = 0;
            // Links will be opened in new window
            pa.newWin = ('newWin' in o) ? o.newWin : true;
            // update corner type
            if ( pa.corner != 'TR' && pa.corner != 'TL' ) {
                pa.corner = 'TR';
            }

            // show only after big image is loaded
            pa.large.img.onload = createAd;

            var prevOnload = window.onload;
            window.onload = function() {
                if ( typeof( prevOnload ) == 'function') {
                    prevOnload();
                }
                
                pa.small.img.src = pa.remoteURL + pa.type +'/'+ pa.corner +'_small.jpg';
                pa.large.img.src = pa.remoteURL + pa.type +'/'+ pa.corner +'_large.jpg';
            };
        }
    };
}());
/*--^-- END of PA ---*/
// If externalCall = fscommand (default)
function camsensePAFlash_DoFSCommand (command, args) {
    var fn = 'CamSensePA.setAdSize';
	if (command == fn) {
        window.setTimeout(fn+'("' + args + '")', 0);
    }
}
