/* ---[ SETUP CLASS ]--- */
/**
 * mdpUploader
 *
 * @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.CoverMaker = function( classPath ){

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

    /* public */

    /* facebook parameters */
    this.facebookApps = {
        allpeoplequilt:{
            api_key:"76111f17a0e6cc266e35fb032efcf569",
            template_id:72734551656
        },
        bhg:{
            api_key : "7927939526727e955997ff2eab01fcdf",
            template_id:125203660477
        },
        fitnessmagazine:{
            api_key:"aa2c352b12be8ed1da7eb7bede53335a",
            template_id:68340715827
        },
        lhj:{
            api_key:"814f8b2a82bbc5599943073dbe34e473",
            template_id:22888114942
        },
        more:{
            api_key:"b3652812a6fcfdc085f9e39c3ffee0ae",
            template_id:54947153332
        },
        parents:{
            api_key:"6da2b86a56ffd73f4d3c0c18d636a92d",
            template_id:72126495925
        },
        scrapbooksetc:{
            api_key:"930c27cc05bd6e444f66f7d34df07cfb",
            template_id:53228704617
        },
        familycircle:{
            api_key:"5a47209a52b09b6a99ff77e76e020f35",
            template_id:72126495925
        }

    };

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


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

    function init(){
        /* initialization code */
        _classPath = classPath;
        _randNumber = Math.random() * 999999999999;
        _divID = "coverMaker" + Math.floor( _randNumber );
        _flashName = "fl" + _divID;
        _divWidth = 890;
        _divHeight = 610;
        _flashWidth = 890;
        _flashHeight = 600;
        _jsReady = false;
        _imageSaved = false;
        _printad = null;
        var domainLocation = document.location + "";
        _domain = domainLocation.substring( 0, domainLocation.indexOf( "/", domainLocation.indexOf( "http://" ) + "http://".length ) );
        _desc = "<h1>Cover Maker</h1><p>Now that you've selected a photo, add a Magazine logo and Text coverlines (just like a real magazine!). Image too small? Add a Border or use a Background color to fill in the space. When you're done designing the perfect magazine cover, hit Finish to save and see sharing options. </p>";
        _cssFile = _domain + "/web/flash/mdp/app/covermaker/coverMakerStyles.css";
        _photoidClass = "pid";
        _subscribeURL = getSubscribeLink();
        _flashMovie = null;

        buildDiv();
        createFlash();
        setUpEventListeners();
        $ES('div.coverMakerImage').each(function(e){
            e.addEvent('click', function(){
                var imgPath = e.getFirst().src;
                var cn = e.getFirst().className;
                var pid = cn.substring( cn.indexOf( _photoidClass + "-" ) + ( ( _photoidClass + "-" ).length ), cn.indexOf( "-" + _photoidClass ) );
                var newPath = imgPath.replace( "_orig", "_full" );
                mdp.CoverMaker.createCover( newPath, pid );
            } );
        });
        changeAllFlashToTransparent();

        /* facebook */
        FB.init(self.facebookApps[ getDomainName( document.domain ) ].api_key,"/common/common/facebook/xd_receiver.jsp");

    }

    function getDomainName( domainName ){

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

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

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

    this.closeCoverMaker = function(){
        _jsReady = false;
        _imageSaved = false;
        window.removeEvent('beforeunload', checkBeforeExit);
        Window.unblock();
    }

    this.createCover = function( imagePath, photoid, cssFile, description ){
        createFlash();

        _jsReady = true;

        this.addVariable("i", imagePath);

        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("a", _printad);

        this.addVariable("cp", _classPath);

        this.addVariable("su", _subscribeURL);

        buildDiv();
        Window.block( _div, '#FFF' );
        $("modal").setStyle('z-index', '20000');
        $("modalmsg").setStyles({
            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.removeEvent('beforeunload', checkBeforeExit);
        } else {

            window.addEvent('beforeunload', checkBeforeExit);
        }
    }

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

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

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

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

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

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

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

        /*  */
        _div = new Element('div', {
            'styles': {
                width: _divWidth,
                height: _divHeight,
                background: 'transparent url()',
                border: '0px solid #000',
                top: "10px",
                left: "10px"
            },
            'id': _divID
        }).setHTML( html );


    }

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

    function changeAllFlashToTransparent(){

        /* embed - add attribute */
        var em = $ES('embed');
        for( var i = 0; i<em.length; i++ ){ 
            em[i].setProperty('wmode', 'transparent');
        }

        /* object - add param tag */
        /* <param value="wmode" name="transparent"/> */
        var ob = $ES('object');
        for( var i = 0; i<ob.length; i++ ){
            var wmode = new Element('param', {'name': "wmode",'value': "transparent"});
            wmode.injectInside(ob[i]);
        }
    }
    
    /**
     * @method createFlash: Builds an SWF Object stub to be re-used.
     */
    function createFlash(){
        _swfObj = new SWFObject("/web/flash/mdp/app/covermaker/CoverMaker.swf?rand=" + _randNumber , _flashName, _flashWidth, _flashHeight, "9", "#FFFFFF");
        _swfObj.addParam("wmode", 'transparent');
        _swfObj.addParam("scale", "noscale");
        _swfObj.addParam("allowScriptAccess", "always");
    }

/* Exxtracted from Flash for reference:::

var fbDataObj:Object = new Object();
                  fbDataObj["cover-url"] = _domain + "/photos/magazine-cover/view-cover/" + _cmid + "/";
                  fbDataObj["covermaker-url"] = _domain + "/photos/magazine-cover/";
                  var siteName:Array = _domain.split( "." );
                  fbDataObj["site-name"] = siteName[1] + "." + siteName[2];
                  fbDataObj["siteurl"] = _domain;
                  fbDataObj["images"] = [{src:_domain + _imagesToEmail[0], href: _domain + "/photos/magazine-cover/"}];
*/


    this.postToFacebook = function( template_data ){
        if(typeof(template_data)=='string'){
            template_data = Json.evaluate( template_data );

            if (location.host.indexOf("test.") > -1) {if (console){console.log(template_data);}}
            
            var href = location.href;
            var thisLocation = ((href.indexOf('?') === -1) ? href : href.substr(0,href.indexOf('?')));            

            var attachment = {
                'name': 'Cover Maker',
                'href':thisLocation,
                'caption': '{*actor*} created a cover using Cover Maker',
                'description':'Use the Cover Maker to create your own cover too! Then print, send, and share your cover with friends and family',
                'media': [{
                    'type': 'image',
                    'src': template_data["images"][0].src,
                    'href': template_data["images"][0].href
                }] };

            if (location.host.indexOf("test.") > -1) {if (console){console.log(attachment);}}

            var action_links = [{'text':'Create A Cover', 'href':thisLocation }];
        }
        if(template_data != null){
            /*FB.Connect.showFeedDialog(self.facebookApps[getDomainName( document.domain )].template_id,template_data, null, null, null, FB.RequireConnect.promptConnect, facebookCallback);*/
            FB.Connect.streamPublish('', attachment, action_links, null, null, facebookCallback);
        }
    };

    function facebookCallback(){
        $$(".posttofacebook").each(function(element){
            element.removeEvents("click");
            element.setAttribute("href","http://www.facebook.com");
            element.setAttribute("target","_blank");
            element.setHTML("View My Cover on Facebook");
        });
    }

    function getSubscribeLink(){
        var urls = {
             "more" : "https://secure.more.com/bhg/store/checkout/partner/index.jsp?promoCode=I903LLD62"
            ,"lhj" : "https://secure.lhj.com/bhg/store/checkout/partner/?promoCode=I901KLD52"
            ,"fitnessmagazine" : "https://secure.fitnessmagazine.com/bhg/store/checkout/partner/?promoCode=I9012LD52"
            ,"parents" : "https://secure.parents.com/bhg/store/checkout/partner/?promoCode=I9014LD19"
            ,"allpeoplequilt" : "https://secure.bhg.com/bhg/store/checkout/partner/?promoCode=I901ALD32"
            ,"bhg" : "https://secure.bhg.com/bhg/store/checkout/partner/?promoCode=I810BLD12"
            ,"scrapbooksetc" : "https://secure.scrapbooksetc.com/bhg/store/checkout/partner/?promoCode=I901SLD32"
        };

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

    /* ---[ EVENT LISTENERS ]--- */
    function setUpEventListeners(){
        $$(".posttofacebook").each(function(element){
            element.addEvent("click",function(){
                mdp.CoverMaker.postToFacebook(mdp.template_data);
            });
        });
    }

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

};


/**
 * Launch this on dom ready
 */
window.addEvent("domready",function(){
    mdp.CoverMaker = new mdp.app.CoverMaker( "mdp.CoverMaker" );
});