/* ---[ SETUP CLASS ]--- */
/**
 * Flair
 *
 * @author Jeremiah LaBresh
 * @requirements SWFObject, MooTools1.11, window.block.js
 * @classDescription Will allow pop up of flash in modal window.
 *
 * @param referenceObject:String ***REQUIRED***
 * 				Name of the instance of the mdpUploader so call backs can be called appropriately
 *
 **/

mdp.app.Flair = function( classPath, relatedImagePathClass ){

    /* ---[ CLASS VARIABLES ]--- */

    /* public */

    /* private */
    var self = this;
    var _classPath, _cssFile, _desc, _div, _divID, _divHeight, _divWidth, _domain, _flashMovie;
    var _flashName, _flashHeight, _flashWidth, _imageSaved, _jsReady, _photoid, _photoidClass;
    var _randNumber, _relatedImagePathClass, _subscribeURL, _swfObj ;


    /* ---[ CONSTRUCTOR ]--- */

    function init(){
        /* initialization code */
        _classPath = classPath;
        _randNumber = Math.random() * 999999999999;
        _divID = "flair" + Math.floor( _randNumber );
        _flashName = "fl" + _divID;
        _divWidth = 890;
        _divHeight = 740;
        _flashWidth = 890;
        _flashHeight = 730;
        _jsReady = false;
        _imageSaved = false;
        _relatedImagePathClass = relatedImagePathClass ? relatedImagePathClass : "flairImageClass";
        
        var domainLocation = document.location + "";
        _domain = domainLocation.substring( 0, domainLocation.indexOf( "/", domainLocation.indexOf( "http://" ) + "http://".length ) );
        _desc = encodeURI( "<h1>Flair</h1><p>Add fun graphics, text, or frames to your photo. Want to accessorize a different photo in your album? Select the thumbnail of the photo you wish to edit below. Be sure to click the \"Save Flair\" button to ensure your changes are saved.</p>");
        _cssFile = _domain + "/web/flash/mdp/app/flair/flairStyles.css";
        _photoidClass = "pid";
        _subscribeURL = getAdUrl();
        _flashMovie = null;

        buildDiv();
        createFlash();
        setUpEventListeners();
        
        changeAllFlashToTransparent();

    }

    function getDomainName( domainName ){

        if(domainName.match( "local" ) ||
           domainName.match( "dev" ) ||
           domainName.match( "test" ) ||
           domainName.match( "www" ) ){
            if(domainName.match( "my." )){
                return domainName.split( "." )[ 2 ];
            } else {
                return domainName.split( "." )[ 1 ];
            }
        } else{
            if( domainName.match("my.") ){
                return domainName.split( "." )[ 1 ];
            } else {
                return domainName.split( "." )[ 0 ];
            }
        }
    }

    function getSubDomainName( domainName ){
        var subDomain = "";
        if(domainName.match( "local" ) ||
           domainName.match( "dev" ) ){
           subDomain = "dev.";
        } else if( domainName.match( "test" ) ){
           subDomain = "test.";
        } else if( domainName.match( "www" ) ){
           subDomain = ""; 
        }
        return subDomain;
    }

    /* ---[ PUBLIC METHODS ]--- */

    this.addVariable = function(varName, varValue, resetFlash){
    	if(resetFlash) createFlash();
		_swfObj.addVariable(varName, varValue);
    };

    this.closeFlair = function(){
        closeFlair( );
    };

    function closeFlair ( ){
        _jsReady = false;
        _imageSaved = false;
        $(window).unbind('beforeunload', checkBeforeExit);
        Window.unblock();
    }

    this.createFlair = function( photoid, cssFile, description ){

        var imgObj = '{"data":[';

        var imgObj2 ={};

        $('.' + _relatedImagePathClass).each( function( i, e ){
            e = $(e);
            var imgPath = e.attr("src") ? e.attr("src") : e.attr("value") ? e.attr("value") : null;
            if( imgPath != null && imgPath != "" ){
                if (i > 0) imgObj += ", ";
                imgObj += '{"img": "' + imgPath + '" }';
            }
        });


        imgObj += ']}';


        createFlash();

        _jsReady = true;
        
        this.addVariable( "i", encodeURI( imgObj ) );

        this.addVariable("u", _domain);

        if(description) _desc = description;
        this.addVariable("d", _desc);

        if(cssFile) _cssFile = cssFile;
        this.addVariable("c", _cssFile);

        if(photoid) _photoid = photoid;
        this.addVariable("p", _photoid);

        this.addVariable("cp", _classPath);

        /* use dyn/dyn for local.  Dev, Test and Prod should be /servlet */
        /*this.addVariable("sp", "/dyn/dyn/servlet/CoverMakerFlashServlet.dyn");*/

        this.addVariable("au", getAdUrl());
        this.addVariable("all", "http://" + getSubDomainName( _domain ) + "images.meredith.com" );
        this.addVariable("ill", "http://" + getSubDomainName( _domain ) + "images.meredith.com" );
        this.addVariable("fll", "http://" + getSubDomainName( _domain ) + "images.meredith.com" );

        buildDiv();
        Window.block( _div, '#FFF' );
        $("#modal").css('z-index', '20000');
        $("#modalmsg").css({
            border: '0px solid #000',
            background: 'transparent url()',
            width: _divWidth,
            height: _divHeight,
            top: "10px",
            left: "10px",
            "z-index":20001
        });



        _swfObj.write( _divID+"flash" );
    };

    this.imageSaved = function( value ){
        _imageSaved = ( value == "true" ? true : false );

        if( _imageSaved ){
            $(window).unbind('beforeunload', checkBeforeExit);
        } else {
            $(window).bind('beforeunload', checkBeforeExit);
        }
    };

    this.isImageSaved = function(){
        return _imageSaved;
    };

    this.sendOmnitureEvent = function( s ){
        if(typeof(window.refreshAdFrame) != "function"){window.refreshAdFrame = function(){/*filler*/};}

        if(typeof(sendLinkEvent) == "function"){
            sendLinkEvent("","" + s);
        }
    };

    this.jsReady = function(){
        return _jsReady;
    };

    this.showHelp = function(){
        window.open("http://images.meredith.com/sharemy/flair/flairHelp.htm","flairHelp","menubar=1,resizable=1,scrollbars=1,width=400,height=400");
    };

    this.saveFlairAndExit = function(){
        closeFlair();
        /* check for method */
        if( mdp.sharemyUploadOnSubmitValidation ) {
            /* call method to see if returns true/false */
            if( mdp.sharemyUploadOnSubmitValidation() ){   

                $("#thumbnail_form").trigger('submit');
            }
        }
    };

    /* ---[ PRIVATE METHODS ]--- */

    function buildDiv(){
        /* create html string */
        var html = "<div id=\"" + _divID + "flash" + "\" ></div>";

        /*  */
        _div = $("<div>").attr('id', _divID).css({
            width: _divWidth,
            height: _divHeight,
            background: 'transparent url()',
            border: '0px solid #000',
            top: "10px",
            left: "10px"
        }).html( html );

    }

    function checkBeforeExit(e){
        /* make sure the user does not lose their data */
        e.returnValue = "If you leave, your Flair will not be saved.";
    }

    function changeAllFlashToTransparent(){

        /* embed - add attribute */
        $('embed').attr('wmode', 'transparent');

        /* object - add param tag */
        /* <param value="wmode" name="transparent"/> */
        $('object').append($("<param>").attr({'name': "wmode",'value': "transparent"}));
    }

    /**
     * @method createFlash: Builds an SWF Object stub to be re-used.
     */
    function createFlash(){
        _swfObj = new SWFObject("/web/flash/mdp/app/flair/Flair.swf?rand=" + _randNumber , _flashName, _flashWidth, _flashHeight, "9", "#FFFFFF");
        _swfObj.addParam("wmode", 'transparent');
        _swfObj.addParam("scale", "noscale");
        _swfObj.addParam("allowScriptAccess", "always");
    }

    function getAdUrl(){
        var urls = {
             "more" : "more.mdp.com"
            ,"lhj" : "lhj.mdp.com"
            ,"fitnessmagazine" : "fitness.mdp.com"
            ,"parents" : "parents.mdp.com"
            ,"allpeoplequilt" : "allpeoplequilt.msim"
            ,"bhg" : "bhg.mdp.com"
            ,"scrapbooksetc" : "bhgscrapbooks.msim"
            ,"livingthecountrylife" : "lcl.mdp.com"
        };
        var rand = Math.floor( Math.random() * 9999999999999 );
        var adPrefix = "http://ad.doubleclick.net/";
        var adSuffix = "/ShareMy;channel=ShareMy;site=" + getDomainName( document.domain ) + ";id=flair;gender=0;age=0000;income=00;genderage=0_0000;ageincome=0000_00;genderincome=0_00;user=0_0000_00;!category=pop;tile=8;sz=234x60;ord="+ rand +"?";



        return urls[ getDomainName( document.domain ) ] ? adPrefix + urls[ getDomainName( document.domain ) ] + adSuffix : "";
    }

    /* ---[ EVENT LISTENERS ]--- */
    function setUpEventListeners(){
        /* none yet */
    }

    /* ---[ RUN ]--- */
    init();

};



