/**
 * adbuilder - handle adbuilder related functionality 
 * 
 * @author: Chanel Munezero <chanel.munezero@escapemg.com>
 */
(function(){
    if(!window.gs) {
        return;
    }

    var adbuilder = window.gs.adbuilder = {
        formUpdateTimeout: null,
        formUpdateTimeoutWait: 1500,
        previewUpdateTimeout: null,
        previewUpdateTimeoutWait: 500,
        submitClicked: false,
        fileLoadingTimeout: null,
        fileLoadingTimeoutWait: 300,

        // fixed scroll info
        initScrollTop: 0,
        scrollHeight: 0,
        scrollOffset: 0,        // initial offset between obj and parent
        maxScrollHeight: 0,     // height of parent
        scrollBottomBuffer: 15,       // pixel buffer for bottom of scrollOffset
        scrollTimeout: null,
        scrollTimeoutWait: 300,

        // editing settings
        isAutoplay: false,
        maxItems: {song:2, artist:-1},
        typeLookup: {},
        /*
        lineTitles: {event:{line1:'Location',line2:'Date/Time'},
                    album:{line1:'Album Name',line2:'Release Date'},
                    artist:{line1:'Description',line2:'Genres'},
                    image:{line1:'',line2:''}},
        */
        lineTitles: {event:{line1:'Description 1',line2:'Description 2'},
                    album:{line1:'Description 1',line2:'Description 2'},
                    artist:{line1:'Description 1',line2:'Description 2'},
                    image:{line1:'',line2:''}},
        linkOrder: {event:['tickets','download','merchandise','other'],
                    album:['merchandise','download','tickets','other'],
                    artist:['download','merchandise','tickets','other'],
                    image:[]},

        empty: null
    };

    adbuilder.init = function(type)
    {
        // handle image uploading form
        $('form.image').attr('target', 'uploadIframe');
        var uploadIframe = $('#uploadIframe').get(0);
        if(uploadIframe) {
            $('form.image').submit(function(event) {
                event = event || window.event;
                debug('form.image.submit', event, 'file value; '+this.file.value, this.file, this.tos)
                if(this.file.value) {
                   if(this.tos.checked) {
                       $('label.file', this).removeClass('error');
                   } else {
                       $('label.file', this).addClass('error');
                       return false;
                   }
                }
                if((this.file.value && this.tos.value) || !this.file.value) {
                    gs.adbuilder.startFileUploadingIndicator();
                    return;
                }
                return false;
            });
            uploadIframe.onload = function(event) {
                event = event || window.event;
                debug('uploadIframe.onload', event);
                gs.adbuilder.iframeUpload(this);
            }
        }
        var type = type || 1;
        // handle input changes
        adbuilder.handleForm();
    }

    adbuilder.doSubmitClicked = function(obj)
    {
        gs.simpleButton.disable(obj);
        adbuilder.submitClicked = true;
        var form = $(obj).parents('form');
        debug('inital form', form, obj);
        if(form.is('.finalSubmit')) {
            debug('form is final submit, grab previous form');
            form = form.prev('form');
        }
        debug('final form', form.get(0));
        adbuilder.updateAd(form);
    }

    adbuilder.resetAdPreview = function()
    {
        var ad = $('#adPreview').children().remove();
        $('#adPreview').append(ad);
        var adImage = $('#adPreviewImage').children().remove();
        $('#adPreviewImage').append(adImage);
    }

    adbuilder.handleForm = function()
    {
        debug('start form handlig code');
        var postFormSubmit = function(json) {
            debug('after adbuilder update ad form submit', json);
            // enable all buttons in forms
            gs.simpleButton.enable($('form button.submit'));
            if(json.bSuccess) {
                // update ad here
                clearTimeout(gs.adbuilder.previewUpdateTimeout);
                gs.adbuilder.previewUpdateTimeout = setTimeout(function() {
                    debug('remove and ad adpreview');
                    if(gs.adbuilder.submitClicked) {
                        // user clicked submit, send them to ad page
                        var adID = $('form.adbuilder').get(0).adID.value;
                        var nextPage = $('form.adbuilder').get(0).nextPage.value;
                        debug('adid and nextpage', adID, nextPage);
                        location.href = nextPage+'?adID='+adID;
                    } else {
                        gs.adbuilder.resetAdPreview();
                    }
                }, gs.adbuilder.previewUpdateTimeoutWait);
            } else {
                debug('error');
            }
        };
        var options = {
            success: postFormSubmit,
            dataType: 'json'
        }
        $('form.otherSteps').ajaxForm(options);
        $('input').each(function() {
            if(!$(this).is('.searchItem')) {
                var input = this;
                //debug('page inputs', input);
                var doUpdate = function() {
                    gs.adbuilder.updateAd($(input).parents('form'));
                }
                input.onkeypress = doUpdate; 
                input.onchange = doUpdate; 
                if($(input).is('.links')) {
                    // input is a link text box
                    var originalText = input.value;
                    var par = input.parentNode; 
                    var parClass = input.parentNode.className;
                    var checkbox = (parClass) ? $(par).siblings('.'+parClass).children('input') : $();
                    //debug('current inputs original text: '+originalText, input, checkbox.get(0));
                    $(input).focus(function() {
                        // user focused on this input
                        if(this.value.match(/^http:\/\/$/) || this.value.match(/^(Download\ Music|Buy\ Merchandise|Buy\ Tickets)$/)) {
                            //this.value = (this.value.match(/^http:\/\/$/)) ? this.value : '';
                            debug('checkbox checke', checkbox.attr('checked'), checkbox);
                            if(checkbox && !checkbox.attr('checked')) {
                                checkbox.attr('checked', true);
                            }
                        }
                    }).blur(function() {
                        var isValid = true;
                        var otherText = $(this).siblings('input').val();
                        this.value = this.value.replace('http://http://','http://');
                        if(otherText=='' || this.value=='') {
                            isValid = false;
                        }
                        if(this.id.match('url')) {
                            // actual link input
                            if(this.value=='http://') {
                                isValid = false;
                            }
                        } else {
                            // title input
                            if(otherText=='http://') {
                                isValid = false;
                            }
                        }
                        if(!isValid) {
                            checkbox.attr('checked', false);
                        }
                        // duplicate image link info to header info, if its not currently set
                        if(this.name=='url' && $('input.descriptionUrl').val()=='http://') {
                            //debug('current input is image link and description link has nothing', this, $('input.descriptionUrl').get(0));
                            $('input.descriptionUrl').val(this.value);
                        }
                    });
                }
            }
        });
        debug('end form');
    }
    
    adbuilder.updateAd = function(form)
    {
        // submits a form with standard timeout
        // see postFormSubmit above
        clearTimeout(adbuilder.formUpdateTimeout);
        adbuilder.formUpdateTimeout = setTimeout(function() {
            debug('do update ad', form.get(0));
            $(form).submit();
        }, adbuilder.formUpdateTimeoutWait);
    }
    
    adbuilder.changeTab = function(tab, submitForm)
    {
        submitForm = (submitForm || typeof submitForm == 'undefined') ? true : false;
        var type = tab.className.replace('active','');
        debug('change to tab: '+type, tab, submitForm);
        if(tab.className.match('active')) {
            debug('tab already active: '+tab.className);
            return false;
        }
        $(tab).addClass('active').parent().siblings().find('a').removeClass('active');
        
        return adbuilder.changeType(type, submitForm);
    }

    adbuilder.selectTypeChange = function(select)
    {
        var submitForm = $(select).parents('form');
        var typeID = $(select).val();
        var type = $('option[value='+typeID+']', select).text().toLowerCase();
        debug('typeid: '+typeID+', type: '+type, $('option[value='+typeID+']', select).get(0));
        type = (type=='upload') ? 'image' : type;

        return gs.adbuilder.changeType(type, submitForm);
    }

    adbuilder.changeType = function(type, submitForm)
    {
        debug('changeType: '+type, submitForm);
        var adb = '#adBuilder';
         
        $('input.adType').attr('value', adbuilder.typeLookup[type]);
        /* 
        var artistHeader = (type=='event') ? 'Other Artists' : 'Similar Artists';
        $('#artistsHeader').text(artistHeader);
         
        var merchandiseText = (type=='album') ? 'Buy The Album:' : 'Buy Merchandise:';
        $('dt.merchandise span', adb).text(merchandiseText);
         
        var linkContainer = $('form.links dl', adb);
        var items = adbuilder.linkOrder[type];
        debug('is items valid: ', items);
        for(var j=0; j<items.length; j++) {
            $(linkContainer).append($('dt.'+items[j], linkContainer));
            $(linkContainer).append($('dd.'+items[j], linkContainer));
        }
        */
        debug('chagne type: ', type);
        var titles = gs.adbuilder.lineTitles[type];
        $('dt.line1').text(titles.line1+':');
        $('dt.line2').text(titles.line2+':');
        
        if(type == 'event') {
            $('ul.steps.descriptions .step4 .event').show();
        } else {
            $('ul.steps.descriptions .step4 .event').hide();
        }
        var imgForm = $('form.image');
        var artistForm = $('form.artist');
        if(type == 'image') {
            debug('type is image');
            $('#adPreview').hide();
            $('#adPreviewImage').show();
            $('p.builder').hide();
            $('p.upload').show();
            $('button.prev', artistForm).unbind('click').removeAttr('onclick');
            $('button.prev', artistForm).click(function() { gs.adbuilder.gotoStep(1); });
            $('button.next', imgForm).unbind('click').removeAttr('onclick');
            $('button.next', imgForm).click(function() { gs.adbuilder.gotoStep(4); });
            //$('button.next', imgForm).hide();
            //$('button.submit', imgForm).show();
            //$('#adBuilder').addClass('upload');
            //$('ul.steps.header li:first').addClass('active').siblings().removeClass('active').hide();
            $('ul.steps.header .step4 a span').text('Step 2');
            $('.stepForm.step4 button.submit').show();
            $('.stepForm.step4 button.next').hide();
            $('ul.steps.header').children('.step2,.step3,.step5').hide();
            adbuilder.gotoStep(1);
        } else {
            debug('type not image');
            $('#adPreview').show();
            $('#adPreviewImage').hide();
            $('p.builder').show();
            $('p.upload').hide();
            $('button.prev', artistForm).unbind('click').removeAttr('onclick');
            $('button.prev', artistForm).click(function() { gs.adbuilder.gotoStep(3); });
            $('button.next', imgForm).unbind('click').removeAttr('onclick');
            $('button.next', imgForm).click(function() { gs.adbuilder.gotoStep(2); });
            //$('button.next', imgForm).show();
            //$('button.submit', imgForm).hide();
            //$('#adBuilder').removeClass('upload');
            //$('ul.steps.header li:first').addClass('active').siblings().show();
            $('ul.steps.header .step4 a span').text('Step 4');
            $('.stepForm.step4 button.submit').hide();
            $('.stepForm.step4 button.next').show();
            $('ul.steps.header').children('.step2,.step3,.step5').show();
        }
       
        if(submitForm) {
            adbuilder.updateAd(imgForm);
        }
        return false;
    }

    adbuilder.gotoStep = function(numStep)
    {
        numStep = numStep || 1;
        debug('step num: '+numStep);
        var activeStep = $('ul.steps.header li').get(numStep - 1);
        var activeDescription = $('ul.steps.descriptions li').get(numStep - 1);
        //var activeContent = $('#adBuilder .content').get(numStep -1);
        var activeContent = $('#adBuilder .stepForm').get(numStep -1);
        // if not visible, then wasn't meant to be seen, so move on to next element
        if(!$(activeStep).is(':visible')) {
            activeStep = $(activeStep).next().get(0);
            activeDescription = $(activeDescription).next().get(0);
            activeContent = $(activeContent).next().get(0);
        }
        debug('actives ', activeStep, activeDescription, activeContent);
        $(activeStep).addClass('active').siblings().removeClass('active');
        $(activeDescription).addClass('active').siblings().removeClass('active');
        $(activeContent).addClass('active').siblings().removeClass('active');
        debug(activeStep, activeDescription, activeContent);
        $.scrollTo('#adBuilder','fast',{offset:{top:-130}});
        return false;
    }

    adbuilder.hoverColorClick = function(obj)
    {
        debug('hover color click', obj);
        //debug($(obj).children(), $(obj).siblings().children());
        $(obj).children().attr('checked','checked');
        $(obj).siblings().children().removeAttr('checked');
        adbuilder.updateAd($(obj).parents('form'));
    }

    adbuilder.startFileUploadingIndicator = function()
    {
        debug('start file uploading indicator');
        clearTimeout(adbuilder.fileLoadingTimeout);
        adbuilder.fileLoadingTimeout = setTimeout(function() {
            //debug('file loading indicator start');
            var text = $('#loadingIndicatorText').text();
            switch(text) {
                case 'Loading': newText = 'Loading.'; break;
                case 'Loading.': newText = 'Loading..'; break;
                case 'Loading..': newText = 'Loading...'; break;
                default: newText = 'Loading';
            }
            $('#loadingIndicatorText').text(newText).show();
            gs.adbuilder.startFileUploadingIndicator();
        }, adbuilder.fileLoadingTimeoutWait);
    }

    adbuilder.iframeUpload = function(iframeObj)
    {
        // end loading indicator
        clearTimeout(gs.adbuilder.fileLoadingTimeout);
        $('#loadingIndicatorText').hide();
        
        debug("load iframe obj",iframeObj);
        var iframeDoc = iframeObj.contentWindow || iframeObj.contentDocument;
        if (iframeDoc.document) {
            iframeDoc = iframeDoc.document;
        }
        var response_str = iframeDoc.body.innerHTML;
        debug('response str', response_str);
        if (response_str) {
            try {
                var json = $.parseJSON(response_str);
            } catch(e) {
                debug('try/catch error', e);
                return;
            }
            debug('json response', json);
            if (json.bSuccess && json.type == adbuilder.typeLookup['image']) {
                // image upload
                //$('#adPreviewImage').html(json.embedCode);
                if(gs.adbuilder.submitClicked) {
                    // take user to ad page
                    var adID = $('form.adbuilder').get(0).adID.value;
                    var nextPage = $('form.adbuilder').get(0).nextPage.value;
                    location.href = nextPage+'?adID='+adID;
                } else {
                    debug('update adpreview iamge, img, url:', json.image, json.imageUrl);
                    $('#adPreviewImage').hide();
                    $('#adPreviewImage img').attr('src', json.image);
                    if(json.imageUrl) {
                        $('#adPreviewImage a').attr('href', json.imageUrl);
                    }
                    $('#adPreviewImage').show();
                    $('#adPreview').hide();
                }
            } else if(json.bSuccess) {
                debug('correct upload, reset ad preview');
                gs.adbuilder.resetAdPreview();
            } else {
                debug('upload error');
                //$('#uploadError').html('<p>' + response.Message + '</p>').show();
            }
        }
    }

    adbuilder.toggleMenuOptions = function(obj) {
        var par = $(obj).parent();
        debug('toggle menu options', obj, par);
        if($(par).is('.adOptions')) {
            debug('par is adoption, toggle ul');
            $(par).toggle().siblings('ul.adbuilder').toggle();
        } else if($(par).is('h3')) {
            debug('par is h3, grab sibling');
            $(par).parent().toggle().siblings('ul.adbuilder').toggle();
        } else {
            debug('par not adoption, must be li');
            $(par).parent().toggle().siblings('div.adOptions').toggle();
        }
        adbuilder.updateAd($(obj).parents('form'));
        return false;
    }

    // override campaigns add new selected methods
    adbuilder.addNewSelected = function(obj) {
        debug('adbuilder add new selected, call campaign', obj);
        var type = ($(obj).parent().is('.song')) ? 'song' : 'artist';
        var max = adbuilder.maxItems[type];
        debug('type, max', type, max);
        var container = $('dd.'+type+'sSelected ul');
        var numContainerChildren = container.children().length;
        if(numContainerChildren == max) {
            var first = container.children(':first').remove();
            var id = $(first).attr('id');
            id = id.split('-');
            id = (id && id[2]) ? id[2] : id;
            var type = ($(first).is('.song')) ? 'songs' : 'artists';
            $('ul.results.'+type+' #sr-'+id).removeClass('added').find('a.add span').text('Add');
            debug('first container id: '+id);
        }
        // check checkbox if artists, and less than 3
        var numChecked = 0;
        $('input.checkbox', container).each(function() {
            if(this.checked) numChecked++;
        });
        debug('numChecked: '+numChecked);
        debug($(obj).siblings('div.hide'));
        if(type=='artist' && numChecked<3) {
            $(obj).siblings('div.hide').find('input.checkbox').attr('checked','checked');
        }
        gs.campaign.addNewSelected(obj);
        // reset original checkbox after it has been cloned
        $(obj).siblings('div.hide').find('input.checkbox').removeAttr('checked');
        adbuilder.updateAd($(container).parents('form'));
        return false;
    }
    adbuilder.removeNewSelected = function(obj) {
        debug('adbuilder remove new selected, call campaign', obj);
        adbuilder.updateAd($(obj).parents('form'));
        gs.campaign.removeNewSelected(obj);
        return false;
    }

    adbuilder.linkChecked = function(obj) {
        //debug('adbuilder link checkbox', obj);
        var numChecked = (obj.checked) ? 1 : 0;
        var isLink = (obj.name.match('link')) ? true : false;
        var par = $(obj).parent().parent().parent().parent();
        var maxChecked = 3;
        //debug("isLink: "+isLink+", numChecked: "+numChecked, par.get(), par.children().get());
        $(par).find('input[type=checkbox]').each(function() {
            //debug('curr checkbox, num:'+numChecked, this);
            if(obj.name!=this.name && this.checked) {
                //debug('not same obj and curr is checked, numcheck:'+numChecked);
                numChecked++;
                if(numChecked>maxChecked) {
                    //debug('numchecked > 3, so current is unchecked');
                    this.checked = false;
                    numChecked--;
                }
            }
        });
        adbuilder.updateAd($(obj).parents('form'));
    }

    adbuilder.activateFlyer = function(obj, adID) {
        if(!adID) { return false; }
        // if class=inactive, currently not enabled, toggle to set it active
        var isEnabled = ($(obj).is('.inactive')) ? 1 : 0;
        var params = {adID: adID, isEnabled: isEnabled};
        debug('adbuilder activateAd: adid: '+adID);
        $.getJSON('/promotion/activateFlyer.json', params, function(json) {
            debug('activateAd json:', json);
            if(isEnabled) {
                $(obj).removeClass('inactive');
            } else {
                $(obj).addClass('inactive');
            }
        });
        return false;
    }

    adbuilder.activeCheckboxToggle = function(obj) {
        debug('pending checkbox toggle', obj);
        var val = (obj.checked) ? '1' : '0';
        var param = 'showActive='+val;
        var url = location.href;
        url = (url.match('\\?')) ? url : url+'?';
        var newUrl = url.replace(/showActive=[0-9]/, param);
        if(url===newUrl) {
            newUrl += '&'+param;
        }
        debug('final url', newUrl, param);
        window.location = newUrl;
    }

    adbuilder.initDeleteFlyer = function(adID) {
        debug('init delete ad', adID);
        if(!adID) { return false; }
        var options = {
            ajax: '/lightboxes/deleteFlyer?adID='+adID,
            onHide: function(hash) {
                gs.modal_hide(hash);
            },
            onLoad: function(hash) {
                gs.modal_show(hash);
            }
        };
        var divinfo = {
            newid: 'deleteFlyer',
            newclass: 'flyer'
        };
        gs.lbFactory.newModalBox(options, divinfo, true);
        return false;
    }

    adbuilder.deleteFlyer = function(adID) {
        debug('delete flyer', adID);
        if(!adID) { return false; }
        var params = {adID: adID, command: 'remove'};
        $.postJSON('/promotion/deleteFlyer.json', params, function(json) {
            debug('return from delete flyer', json);
            //gs.lbFactory.disposeModalBox($("#deleteSong"));
            location.href = '/promotion/myFlyerCampaigns';
        });

        return false;
    }

    adbuilder.changePreview = function(adID) {
        debug('change preview. adid:',adID);
        adID = (adID=='default') ? 0 : adID;
        $('#adPreview').hide();
        var newHtml = $('#adPreview').html();
        debug('new html: ', newHtml);
        newHtml = newHtml.replace(/adID\=([0-9]+)/g,'adID='+adID);
        $('#adPreview').html(newHtml);
        $('#adPreview').show();
    }
    adbuilder.changeStart = function(input) {
        debug('change start, cur input', input);
        if(input.value=='template') {
            debug('dealing with template');
            $('#flyerStartScratch').siblings('.note').hide();
            $('#flyerStartTemplate').siblings('.note').show();
        } else {
            debug('dealing with scratch');
            $('#flyerStartTemplate').siblings('.note').hide();
            $('#flyerStartScratch').siblings('.note').show();
        }
    }

})(); 
