function moo(el){
    return document.id(el);
}

var globalvars = {
    imagecontrol : {
        widgetType : null,
        name : null,
        uid : null,
        form : null,
        uploadImageURL : null,
        browseImageGalleryURL : null
    }
};

var ImageControl = {
    uploadImage : function(param){
        if(param != null){
            globalvars.imagecontrol.widgetType = param.widgetType;
            globalvars.imagecontrol.name = param.name;
            globalvars.imagecontrol.uid = param.uid;
            globalvars.imagecontrol.form = param.form;
        }
        switch(param.widgetType){
            case 'singleimagecontrol': {
                window.open(
                    globalvars.imagecontrol.uploadImageURL + '?size=100&type=custom', 
                    'winuploadphoto',
                    'width=600,height=200,top=50,left=50'
                );        
                break;
            }
            case 'screenshotscontrol': {
                window.open(
                    globalvars.imagecontrol.uploadImageURL + '?size=100&type=thumbnail', 
                    'winuploadphoto',
                    'width=600,height=200,top=50,left=50'
                );        
                break;
            }
        }
          
    },
    browseImageGallery : function(param){
        if(param != null){
            globalvars.imagecontrol.widgetType = param.widgetType;
            globalvars.imagecontrol.name = param.name;
            globalvars.imagecontrol.uid = param.uid;
            globalvars.imagecontrol.form = param.form;
        }
        switch(param.widgetType){
            case 'singleimagecontrol': {
                window.open(
                    globalvars.imagecontrol.browseImageGalleryURL + '?size=100&type=custom', 
                    'winbrowsephotos',
                    'width=625,height=400,top=50,left=50'
                );       
                break;
            }
            case 'screenshotscontrol': {
                window.open(
                    globalvars.imagecontrol.browseImageGalleryURL + '?size=100&type=thumbnail', 
                    'winbrowsephotos',
                    'width=625,height=400,top=50,left=50'
                );
                break;
            }
        }
    },
    removeImage: function(param){
        switch(param.widgetType){
            case 'singleimagecontrol':{
                var imagectrl = param.form.getElement("div[uid='" + param.uid + "']");
                if(imagectrl.getElement('.widget-image-control-repoid'))
                    imagectrl.getElement('.widget-image-control-repoid').destroy();
                if(imagectrl.getElement('.widget-image-control-image'))
                    imagectrl.getElement('.widget-image-control-image').destroy();
                if(imagectrl.getElement('.remove-image-button'))
                    imagectrl.getElement('.remove-image-button').disabled = true;
                break;
            }
            case 'screenshotscontrol': {
                var screenshotsctrl = param.form.getElement("div[uid='" + param.uid + "']");
                if(!screenshotsctrl.getElements('.screenshots-repoid')) return; 
                screenshotsctrl.getElements('.screenshots-repoid').each(function(el){
                    if(el.value == param.deleteImageRepoID) el.destroy();
                });
                screenshotsctrl.getElements('.screenshots-images').each(function(el){
                    if(el.get('repoid') == param.deleteImageRepoID) el.destroy(); 
                });
                break;
            }
        }        
    },
    updatePhoto : function(url, photoid){
        if(globalvars.imagecontrol.widgetType == null) 
            globalvars.imagecontrol.widgetType = 'singleimagecontrol';
        
        switch(globalvars.imagecontrol.widgetType){  
            case 'singleimagecontrol' : {
                var imagectrl = globalvars.imagecontrol.form.getElement("div[imageControlName='" + globalvars.imagecontrol.name + "']");
                
                if(imagectrl.getElement('.widget-image-control-image')){
                    imagectrl.getElement('.widget-image-control-image').src = url;
                }else{
                    new Element('img',{
                        'class' : 'widget-image-control-image',
                        src : url,
                        styles : {
                            'float' : 'left',
                            verticalAlign : 'middle',
                            height : (imagectrl.offsetHeight - 12),
                            marginRight : 10,
                            border: 'solid 3px #fff',
                            'border-radius' : '5px'
                        }
                    }).inject(imagectrl.getElement('.widget-image-control-main'),'top');
                }
                
                if(imagectrl.getElement('.widget-image-control-repoid')){
                    imagectrl.getElement('.widget-image-control-repoid').set('value', photoid);
                }else{
                    new Element('input',{
                        type : 'hidden',
                        name : globalvars.imagecontrol.name + '[repoid]',
                        'class' : 'widget-image-control-repoid',
                        value : photoid
                    }).inject(imagectrl.getElement('.widget-image-control-main'));
                }
                
                //enabling the remove image button
                if(imagectrl.getElement('.remove-image-button')){
                    imagectrl.getElement('.remove-image-button').disabled = false;
                }               
                break;
            }
            case 'screenshotscontrol' : {
                var ctrl = globalvars.imagecontrol.form.getElement("div[uid='" + globalvars.imagecontrol.uid + "']");
                if(ctrl.getElement('.widget-screenshots-control-metadata')){
                    //adding the image repoid
                    new Element('input',{
                        type: 'hidden',
                        name: globalvars.imagecontrol.name + '[]',
                        value: photoid,
                        'class': 'screenshots-repoid'
                    }).inject(ctrl.getElement('.widget-screenshots-control-metadata'));
                }
                if(ctrl.getElement('.widget-screenshots-control-imagelist')){
                    //adding new image
                    var screenshot = new Element('img', {
                        repoid: photoid,
                        uid: globalvars.imagecontrol.uid,
                        src: url,
                        'class': 'screenshots-images',
                        styles: {
                            'float': 'left',
                            'border': 'solid 5px #fff',
                            'border-radius': '5px',
                            'margin' : '10px'
                        },
                        events: {
                            'mouseenter' : function(){
                                //creating a mask covering image
                                var img = moo(this);
                                var mask = new Element('div',{
                                    repoid: img.get('repoid'),
                                    uid: img.get('uid'),
                                    html: '<div style="text-align: center; padding: 10px; padding-top: 25px; color: #fff;"><img alt="" src="' + BASE_URL + '/images/bttns/delete.png" style="vertical-align: middle" /> Click To Delete</div>',  
                                    styles: {
                                        position: 'absolute',
                                        left: img.offsetLeft,
                                        top: img.offsetTop,
                                        width: img.offsetWidth,
                                        height: img.offsetWidth,
                                        backgroundColor: 'black',
                                        'border-radius': '5px',
                                        opacity: 0.80,
                                        cursor: 'pointer'
                                    },
                                    events: {
                                        'mouseleave': function(){
                                            moo(this).destroy();
                                        },
                                        'click': function(){
                                            var form = moo(this).retrieve('form');
                                            var uid = moo(this).get('uid');
                                            var name = form.getElement("div[uid='" + uid + "']").get("controlname");
                                            ImageControl.removeImage({
                                                widgetType: 'screenshotscontrol',
                                                'form': form,
                                                'name': name,
                                                'uid': uid,
                                                deleteImageRepoID: moo(this).get('repoid')
                                            });
                                            moo(this).destroy();
                                        }
                                    }
                                }).inject(moo(this).getParent('.widget-screenshots-control-imagelist'));
                                mask.store('form', img.retrieve('form'));
                            }
                        }
                    }).inject(ctrl.getElement('.widget-screenshots-control-imagelist'), 'top');
                    screenshot.store('form', globalvars.imagecontrol.form);
                }
                break;
            }
        }
        
        //resetting the global vars for  image controls
        globalvars.imagecontrol.name = null;
        globalvars.imagecontrol.uid = null;
        globalvars.imagecontrol.form = null;
        globalvars.imagecontrol.widgetType = null;
    },
    showBigImage: function(photoid){
        //getting the view area height
        var imageHeight = (0.8 * window.screen.availHeight).toInt();   
             
        new Request.JSON({
            url: BASE_URL + '/home/getimagehandler',
            data: {image: photoid, 'imageHeight': imageHeight},
            onRequest: function(){
                //creating mask
                new Element('DIV',{
                    id: '_imagescreen',
                    styles: {
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        width: window.document.body.offsetWidth,
                        height: window.document.body.offsetHeight,
                        backgroundColor: 'black',
                        opacity: 0.85,
                        zIndex: 2000
                    },
                    events: {
                        'click': function(){                            
                            if(moo('big-image') != undefined)
                                moo('big-image').destroy();
                            moo(this).destroy();
                        }
                    }
                }).inject(window.document.body);
                new Element('DIV',{
                    'id': '_loaderstatus',
                    styles: {
                        position: 'absolute',
                        top: window.getScroll().y + (window.screen.availHeight - 50)/5,
                        left: (window.screen.availWidth - 200) / 2,
                        width: 200,
                        height: 50,
                        color: 'white',
                        fontSize: 16,
                        textAlign: 'center',
                        zIndex: 3000
                    },
                    html: 'Loading ...'
                }).inject(window.document.body);
            },
            onSuccess: function(response){
                var image = response.image;
                Asset.image(image.url, {
                    id: 'myImage',
                    title: 'myImage',
                    onLoad: function(){
                        moo('_loaderstatus').destroy();
                        new Element('div',{
                            id: 'big-image',
                            styles: {
                                position: 'absolute',
                                padding: 25,
                                top: window.getScroll().y + (imageHeight - (image.height + 25))/2,
                                left: (window.screen.availWidth - (image.width + 50))/2,
                                width: 0,
                                height: 0,
                                zIndex: 3000,
                                backgroundColor: 'white',
                                overflow: 'hidden'
                            },
                            html: '<img alt="" src="' + image.url + '" /><div style="text-align: right; padding: 5px; height: 25px;"><a href="javascript:void(0);" onclick="moo(\'_imagescreen\').fireEvent(\'click\', this);" style="color: black; text-decoration: none; font-size: 22px;">X Close</a></div>' 
                        }).inject(window.document.body);
                        new Fx.Morph(moo('big-image'),{transition: Fx.Transitions.Sine.easeIn}).start({
                            'width' : image.width,
                            'height' :  image.height + 25
                        });     
                    }
                });
            },
            onFailure: function(){
                
            }
        }).send();
    }
};

var FormController = {
    openDialog : function(el, options){
        if(el){
            if(options != undefined){
                if(options.clearFields != undefined && options.clearFields == false){
                    //do nothing
                }else{
                    this.clearFields(el);        
                }
            }else{
                this.clearFields(el);
            }
            new Fx.Slide(el).slideIn().chain(function(){
                el.scrollIntoView();
            });            
        }
    },
    closeDialog : function(el){
        if(el){
            new Fx.Slide(el).slideOut();
        }
    },
    clearFields : function(el){
        if(el){
            el.getElements("input[type='text'],textarea").each(function(el){ el.value = '' });
            //resetting image control, if any
            if($$('.widget-image-control-image').length != 0)
                $$('.widget-image-control-image').pick().destroy();
            if($$('.widget-image-control-repoid').length != 0)
                $$('.widget-image-control-repoid').pick().destroy();
            //resetting screenshots control, if any
            if($$('.screenshots-repoid').length != 0)
                $$('.screenshots-repoid').each(function(el){el.destroy();});
            if($$('.screenshots-images').length != 0)
                $$('.screenshots-images').each(function(el){el.destroy();});
            //resetting CKEditor
            if(typeof CKEDITOR !== 'undefined'){                
                for(var i in CKEDITOR.instances){
                    CKEDITOR.instances[i].setData('');
                }
            }
        }
    },
    postForm: function(el, url, options){
        var form = el.getElement('form');
        if(!form) return;
        //updating element of all CKEditor instance
        if(typeof CKEDITOR !== 'undefined'){
            for(var i in CKEDITOR.instances){
                CKEDITOR.instances[i].updateElement();          
            }
        }
        new Request.JSON({
            url : url,
            data : form.toQueryString(),
            method : 'POST',
            onRequest : function(){
                FormController.FormHelpers.mask.show(el);                     
                //showing wait text
                new Element('div',{
                    id : '_waittext',
                    styles : {
                        textAlign : 'center',
                        padding: 10,
                        position: 'absolute',
                        bottom: 0,
                        left: 0,
                        zIndex : 3000,
                        width : el.offsetWidth,
                        color : '#ccc',
                        fontSize : 16
                    },
                    html : '<img alt="" src="' + BASE_URL +  '/images/processing.gif" /> Please wait ...'
                }).inject(el);
            },
            onSuccess : function(response){
                FormController.FormHelpers.mask.hide();
                FormController.FormHelpers.waittext.hide();
                if(response.error){
                    alert(response.errormsg);
                }else if(response.success){
                    alert(response.successmsg);
                    if(!options.doNotCloseDialog)FormController.closeDialog(el);
                    if(options && options.updateList) FormController.updateList(options.updateElement, options.updateURL);
                    if(options.callback) options.callback();
                }
            },
            onFailure : function(){
                FormController.FormHelpers.mask.hide();
                FormController.FormHelpers.waittext.hide();
                alert('Failed to post the form. Please re-try again.');
            }
        }).send();
    },
    loadFormData : function(el, url, data, callback){
        new Request.JSON({
            url : url,
            data : data,
            method : 'POST',
            onRequest : function(){
                FormController.FormHelpers.mask.show(el);                     
                FormController.FormHelpers.waittext.show(el);
            },
            onSuccess : function(response){
                FormController.FormHelpers.mask.hide();
                FormController.FormHelpers.waittext.hide();
                if(response.error){
                    alert(response.errormsg);
                }else if(response.success){
                    callback(response.data);
                }
            },
            onFailure : function(){
                FormController.FormHelpers.mask.hide();
                FormController.FormHelpers.waittext.hide();
                alert('Failed to post the form. Please re-try again.');
            }
        }).send();
    },
    updateList : function(el, url){
        new Request.HTML({
            url : url,
            update : el,
            onRequest : function(){
                FormController.FormHelpers.mask.show(el);
                FormController.FormHelpers.waittext.show(el);
            },
            onFailure : function(){
                FormController.FormHelpers.mask.hide();
                FormController.FormHelpers.waittext.hide();                
                alert("Failed to update list. Re-try again.");
            } 
        }).send();
    },    
    FormHelpers : {
        mask : {
            show : function(el){
                el.setStyle('position', 'relative');
                new Element('div',{
                    id : '_mask',
                    styles : {
                        backgroundColor: 'black',
                        opacity : 0.8,
                        position : 'absolute',
                        top : 0,
                        left : 0,
                        width : el.offsetWidth,
                        height : el.offsetHeight,
                        zIndex : 2000,
                        'border-radius' : '5px'
                    }
                }).inject(el); 
            },
            hide : function(){
                if(moo('_mask')) moo('_mask').destroy();
            }
        },
        waittext : {
            show : function(el, text, options){
                el.setStyle('position', 'relative');
                new Element('div',{
                    id : '_waittext',
                    styles : {
                        textAlign : 'center',
                        padding: 25,
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        zIndex : 3000,
                        width : el.offsetWidth,
                        color : '#ccc',
                        fontSize : 16
                    },
                    html : '<img alt="" src="' + BASE_URL +  '/images/processing.gif" /> ' + (text == null ? 'Please wait ....' : text)
                }).inject(el);
                if(options !== undefined){
                    if(options.adjustTop !== undefined && options.adjustTop == true){
                        moo('_waittext').setStyles({
                            top: moo(document.body).getScroll().y + 150 
                        });
                    }
                    if(options.padding !== undefined){
                        moo('_waittext').setStyle('padding', options.padding);
                    }
                }
            },
            hide : function(){
                if(moo('_waittext')) moo('_waittext').destroy();
            }
        }
    }
};

var ActionController = {
    subscribe: function(email, el, url){
        if(!confirm("Are you sure to continue?")) return;
        new Request.JSON({
            url: url,
            data: {'email': email.value, 'resetvalue': email.retrieve('resetvalue')},
            onRequest: function(){
                FormController.FormHelpers.mask.show(el);
                FormController.FormHelpers.waittext.show(el, 'Please wait...', {padding: 10});
            },
            onSuccess: function(response){
                FormController.FormHelpers.waittext.hide();
                FormController.FormHelpers.mask.hide();
                if(response.error){
                    alert(response.errormsg);
                }else if(response.success){
                    alert('Successfully subscribed to receive our free newsletter.');
                    email.value = email.retrieve('resetvalue');
                }
            },
            onFailure: function(){
                FormController.FormHelpers.waittext.hide();
                FormController.FormHelpers.mask.hide();
                alert('Request failed. Please re-try again.');
            }
        }).send();
    }  
};

window.addEvent('domready', function(){
    $$('.slider-form').each(function(el){
        new Fx.Slide(el).slideOut();
    }); 
});
