/***********************************************************************
 @ filename            : js/user.js
 @ author              : Ken Wang
 @ description         : User class
 @ created             : 2007-11-12
 @ modified            : 2008-05-10
 @ requires            : mootools.js
 ***********************************************************************/

var User = {

    cons:{
    },
    vars:{
    },

    Init:function() {
        User.InitLoginForm();
        new SmoothScroll();
    },



    /***** generic-form *****/
    Back:function( formObj )
    {
        if( formObj && typeof(formObj.back_url) != 'undefined' && formObj.back_url.value != '' )
        { location.href = formObj.back_url.value; }
        else
        { history.go(-1); }
    },

    /***** login-form *****/
    InitLoginForm:function(){
        if( !$('login-form') ) return;
        $('login-form').onsubmit = function(){ return User.CheckLoginForm(this); }
        if( $('login-form').username.value == '' )
        { $('login-form').username.focus(); }
    },

    CheckLoginForm:function( formObj ){
        if( formObj.username.value.trim().length < 3 )
        { alert('Please enter your username'); formObj.username.focus(); return false; }
        if( formObj.passwd.value.trim().length < 3 )
        { alert('Please enter your password'); formObj.passwd.focus(); return false; }
        return true;
    },

    /***** Assets *****/
    ReloadAssets:function()
    {
        $('assets-loader-1').addClass('action-loader-on');
        new Ajax('./contents.php?mode=assets&ajax=1&rand='+Math.random(), {
            method: 'get',
            update: $('files-list-ul-1'),
            onComplete: function(){
                if($('assets-count')) { $('assets-count').setText( $$('ul#files-list-ul-1 li').length ); }
                $('assets-loader-1').removeClass('action-loader-on');
            }
        }).request();
    },

    DelAsset:function( url, item_id )
    {
        $(item_id).addClass('purging');
//		alert(item_id);

 	 var filename = document.getElementById('filename-' + item_id.substr(5)).innerHTML
	     filename = filename;
        if( !confirm("DELETE FILE: " + filename.toUpperCase() + "\n\nYou are going to completely remove this item from the server.\nIf it is in use on a webpage, it will disappear from that page!\nAre you sure you want to delete this file?") )
        { $(item_id).removeClass('purging');  return; }
        new Ajax(url+'&ajax=1&rand='+Math.random(), {
            method: 'get',
            evalResponse: true
        }).request();
    },

    PurgeAssetItem:function( item_id )
    {
        if($(item_id))
        {
            var purgeFx = new Fx.Styles( item_id, {duration:500,transition:Fx.Transitions.Quad.easeOut} );
            purgeFx.start({'height':0,'opacity':0}).chain(function(){ $(item_id).remove(); });
            if($('assets-count'))
            { $('assets-count').setText( ($('assets-count').getText().toInt()-1) ); }
        }
    },
    /***** Contact Form *****/
    ToggleContactField:function( field_id )
    {
        for( var i=1; i<=10; i++ )
        {
            if( typeof field_id == 'number' && field_id != i ) continue;
            var on = ( $('field_'+i+'[type]').value != 'none' ) ? true : false;
            $('field_'+i+'[label]').disabled = !on;
            $('field_'+i+'[required]').disabled = !on;
        }
    },

    /***** Galleries *****/
    ReloadGalleryImages:function( gallery_id )
    {
        $('gallery-images-loader-1').addClass('action-loader-on');
        var myRequest = new Request('./contents.php?mode=gallery_images&gallery_id='+gallery_id+'&ajax=1&rand='+Math.random(), {
            method: 'get',
            update: $('files-list-ul-1'),
            onComplete: function(){
                if($('gallery-images-count')) { $('gallery-images-count').setText( $$('ul#files-list-ul-1 li').length ); }
                $('gallery-images-loader-1').removeClass('action-loader-on');
            }
        })
		myRequest.send();
    },

    DelGalleryImage:function( url,item_id,item_title,resultMessage )
    {
        $(item_id).addClass('purging');
    	//$(item_id).setStyle('background','#fb6c6c');
        if( !confirm("You have chosen to delete the image '" + item_title + "' from this gallery.\nThis cannot be undone.\nDo you want to continue?") ) {
        	$(item_id).removeClass('purging');  return;
        }
        var req = new Request.HTML({url:url+'&ajax=1&rand='+Math.random(),
        	onRequest: function() {
				new Fx.Tween($(item_id),{
					duration:300
				}).start('background-color', '#fb6c6c');
			},
        	onSuccess: function(html) {
        		//$(item_id).setStyle('display','none');
        		new Fx.Slide($(item_id),{
        			duration:300,
        			onComplete: function() {
        				$(item_id).dispose();
					}
        		}).slideOut();
        		var textMessage = 'Image "'+item_title+'" deleted successfully.'; $(resultMessage).set('text',textMessage);
        	},
    		onFailure: function() {
        		$(item_id).removeClass('purging');
        		var textMessage = 'Error occured. Could not delete "'+item_title+'".'; $(resultMessage).set('text',textMessage);
        	}
        });
        req.send();
    },

    PurgeGalleryImageItem:function( item_id )
    {
        if($(item_id))
        {
            var purgeFx = new Fx.Styles( item_id, {duration:500,transition:Fx.Transitions.Quad.easeOut} );
            purgeFx.start({'opacity':0}).chain(function(){ $(item_id).remove(); });
            if($('gallery-images-count'))
            { $('gallery-images-count').setText( ($('gallery-images-count').getText().toInt()-1) ); }
        }
    },

    EditGalleryImageForm:function( url, item_id )
    {
        url+= '&rand='+Math.random();
        $('app-floater').empty();

        User.RaiseCurtain();
        User.vars.giAjax = new Ajax(url,{
            method:'get',update:'app-floater',evalScripts:true,
            onComplete:function(){
                User.ShowAppFloater();
                $('af-body').makeResizable({
                    modifiers: {x:false,y:'height'},
                    limit:{y:[50,600]},
                    handle:$('af-body-resizer')
                });
                $('app-floater').makeDraggable({
                    container: $('section-outline'),
                    handle:$('af-header')
                });
                User.ShowAppFloater();
            }
        }).request();
    },

    EditGalleryImage:function( formObj )
    {
        var item_id = 'gallery-image-'+formObj.image_id.value;
        $(formObj.id+'-loading').setStyle('visibility','visible');
        User.vars.giAjax = $(formObj.id).send({
            update:item_id,
            onComplete:function(){
                User.DropCurtain();
                var updateFx = new Fx.Styles( item_id, {duration:2000,transition:Fx.Transitions.Quad.easeOut} );
                updateFx.start({'background-color':['#FFFFCC','#FFFFFF']}).chain(function(){$(item_id).setStyle('background-color','')});
            }
        });
    },

    CalcGalleryImageResize:function( inp )
    {   // minimum shrink size = 200x200
        var formObj = inp.form;
        var ow = formObj.old_width.value.toInt(); // old width
        var oh = formObj.old_height.value.toInt(); // old height
        var cp = formObj.resize_proportions.checked; // constrain proportions
        var w2h = oh/ow; // width-to-height multiplier
        var h2w = ow/oh; // height-to-width multiplier
        var irw = formObj.resize_width; // input: resize width
        var irh = formObj.resize_height; // input: resize height
        if( inp.name == 'resize_width' )
        {   // check if resize_width is valid and within range
            var nw = irw.value = irw.value.toInt(); // new width
            if( isNaN(nw) || nw < 200 || nw > ow )
            { alert("Invalid width (must be between 200 and "+ow+" px)"); irw.value = ow; irh.value = oh; return; }
            // update new height
            var nh = irh.value = ( cp ? ( nw*w2h ).round() : irh.value.toInt() ); // new height
            if( isNaN(nh) || nh < 200 || nh > oh )
            { alert("New height is not within accepted range (200 to "+oh+" px)"); irw.value = ow; irh.value = oh; return; }
            //irh.focus(); irh.select(); return;
        }
        else
        {   // check if resize_height is valid and within range
            var nh = irh.value = irh.value.toInt(); // new height
            if( isNaN(nh) || nh < 200 || nh > oh )
            { alert("Invalid height (must be between 200 and "+oh+" px)"); irw.value = ow; irh.value = oh; return; }
            var nw = irw.value = ( cp ? ( nh*h2w ).round() : irw.value.toInt() ); // new width
            if( isNaN(nw) || nw < 200 || nw > ow )
            { alert("New width is not within accepted range (200 to "+ow+" px)"); irw.value = ow; irh.value = oh; return; }
        }
        return true;
    },

/*  images (logos etc)  */
EditImageForm:function( url)
    {
        url+= '&rand='+Math.random();
        $('app-floater').empty();

        User.RaiseCurtain();
        User.vars.giAjax = new Ajax(url,{
            method:'get',update:'app-floater',evalScripts:true,
            onComplete:function(){
                User.ShowAppFloater();
                $('af-body').makeResizable({
                    modifiers: {x:false,y:'height'},
                    limit:{y:[50,600]},
                    handle:$('af-body-resizer')
                });
                $('app-floater').makeDraggable({
                    container: $('section-outline'),
                    handle:$('af-header')
                });
                User.ShowAppFloater();
            }
        }).request();
    },

    EditImage:function( formObj )
    {
        var item_id = 'gallery-image-'+formObj.image_id.value;
        $(formObj.id+'-loading').setStyle('visibility','visible');
        User.vars.giAjax = $(formObj.id).send({
            update:item_id,
            onComplete:function(){
                User.DropCurtain();
                var updateFx = new Fx.Styles( item_id, {duration:2000,transition:Fx.Transitions.Quad.easeOut} );
                updateFx.start({'background-color':['#FFFFCC','#FFFFFF']}).chain(function(){$(item_id).setStyle('background-color','')});
            }
        });
    },

    CalcImageResize:function( inp )
    {   //  minimum shrink size = 60x60
        var formObj = inp.form;
        var ow = formObj.old_width.value.toInt(); // old width
        var oh = formObj.old_height.value.toInt(); // old height
        var cp = formObj.resize_proportions.checked; // constrain proportions
        var w2h = oh/ow; // width-to-height multiplier
        var h2w = ow/oh; // height-to-width multiplier
        var irw = formObj.resize_width; // input: resize width
        var irh = formObj.resize_height; // input: resize height
        if( inp.name == 'resize_width' )
        {   // check if resize_width is valid and within range
            var nw = irw.value = irw.value.toInt(); // new width
            if( isNaN(nw) || nw < 60 || nw > ow )
            { alert("Invalid width (must be between 60 and "+ow+" px)"); irw.value = ow; irh.value = oh; return; }
            // update new height
            var nh = irh.value = ( cp ? ( nw*w2h ).round() : irh.value.toInt() ); // new height
            if( isNaN(nh) || nh < 60 || nh > oh )
            { alert("New height is not within accepted range (60 to "+oh+" px)"); irw.value = ow; irh.value = oh; return; }
            //irh.focus(); irh.select(); return;
        }
        else
        {   // check if resize_height is valid and within range
            var nh = irh.value = irh.value.toInt(); // new height
            if( isNaN(nh) || nh < 60 || nh > oh )
            { alert("Invalid height (must be between 60 and "+oh+" px)"); irw.value = ow; irh.value = oh; return; }
            var nw = irw.value = ( cp ? ( nh*h2w ).round() : irw.value.toInt() ); // new width
            if( isNaN(nw) || nw < 60 || nw > ow )
            { alert("New width is not within accepted range (60 to "+ow+" px)"); irw.value = ow; irh.value = oh; return; }
        }
        return true;
    },

    /* Mailing List */
    DelMailingListees:function( formObj ){
        // check if at least one subscriber selected
        var chosen = User._MailingListeesChosen( formObj );
        if( chosen == 0 )
        { alert("Please choose at least one subscriber to remove."); return; }
        if( !confirm("Are you sure you want to remove "+chosen+" subscriber(s)?") )
        { return; }
        // change form mode
        formObj.mode.value = 'mailinglist_del';
        $( formObj.id ).send({
            update:$('subscribers-list-ul-1'),
            onComplete:function(){
                $('subscribers-count').setText( $('subscribers-list-ul-1').getElementsByTagName('li').length );
            },
            onFailure:function(){
                alert( "Error: please try again later." );
            }
        });
    },

    _MailingListeesChosen:function( formObj )
    {
        if( typeof(formObj['subscribers[]']) == 'undefined' )
        { return 0; }
        if( typeof(formObj['subscribers[]'].length) != 'number' ) // only one checkbox
        { return (!formObj['subscribers[]'].checked ? 0:1 ); }
        if( typeof(formObj['subscribers[]'].length) == 'number' ) // more than one
        {
            var count = 0;
            for( var i=0; i<formObj['subscribers[]'].length; i++ )
            {
                if( formObj['subscribers[]'][i].checked )
                { count++; }
            }
            return count;
        }
        return 0;
    },

    MailingListSelAll:function( formObj, onoff )
    {
        if( typeof(formObj['subscribers[]'].length) == 'number' )
        {
            for( var i=0; i<formObj['subscribers[]'].length; i++ )
            { formObj['subscribers[]'][i].checked = onoff; }
        }
        else if( typeof(formObj['subscribers[]']['type']) == 'string' && formObj['subscribers[]'].type == 'checkbox' )
        { formObj['subscribers[]'].checked = onoff; }
    },

    SendMailingList:function( formObj )
    {   // at least one subscriber chosen?
        var chosen = User._MailingListeesChosen( formObj );
        if( chosen == 0 )
        { alert("Please choose at least one subscriber."); return; }
        // subject/body check
        if( formObj.subject.value.trim().length < 5 )
        { alert("Please enter subject."); return; }
        if( formObj.mail_body.value.trim().length < 10 )
        { alert("Please enter message body."); return; }
        // update mode
        formObj.mode.value = 'mailinglist_send';
        // send it
        $( formObj.id ).send({ evalResponse:true });
    },

	//  public page image
	ShowImagePage:function(url)
    {
        $('app-floater').empty();

        User.RaiseCurtain();
        User.vars.giAjax = new Ajax(url,{
            method:'get',update:'app-floater',evalScripts:true,
            onComplete:function(){
                User.ShowAppFloater();
                $('af-body').makeResizable({
                    modifiers: {x:false,y:'height'},
                    limit:{y:[50,600]},
                    handle:$('af-body-resizer')
                });

                $('app-floater').makeDraggable({
                    container: $('section-outline'),
                    handle:$('af-header')
                });
                User.ShowAppFloater();
            }
        }).request();
    },

    /* AppFloater */
    ShowAppFloater:function(){
        var afSizes = $('app-floater').getSize();
        $('app-floater').setStyles({left:((window.getWidth()-afSizes.size.x)/2).toInt(),top:window.getScrollTop()+(window.getHeight()/3).toInt()});
    },

    HideAppFloater:function(){
        $('app-floater').setStyles({left:'-999em'});
    },

    /* AppCurtain */
    RaiseCurtain:function(){
        $('app-curtain').setStyles({left:0, height:window.getScrollHeight(), opacity:0});
        if(window.ie6){ $('section-outline').addClass('hide-dropdowns'); }
        $('app-curtain').addEvent('click',User.DropCurtain);
        User.vars.Fader = new Fx.Style( 'app-curtain', 'opacity', {duration:300} );
        User.vars.Fader.start(0,0.5);
    },

    DropCurtain:function(){
        $('app-curtain').removeEvent('click');
        User.HideAppFloater();
        User.vars.Fader.start(0.5,0).chain(function(){
            $('app-curtain').setStyles({left:'-999em',height:0});
            if(window.ie6){ $('section-outline').removeClass('hide-dropdowns'); }
        });
    },

	SelectImage:function(img,gallery) {
	alert (img + ' ' + gallery + ' ' + window.location);
//		eval("document.getElementById('af-image').src='" + img + "'");
//		$('af-image').src(img);
	},
    EOS:0
}

function gotoPage( page_id, form_name )
{
    var formObj = document.forms[form_name];
    formObj.page.value = page_id;
    if( typeof formObj.onsubmit == 'function' )
    { if( formObj.onsubmit() ) { formObj.submit(); return; } }
    else
    { formObj.submit(); }
}

function orderPage( field, form_name )
{
    var formObj = document.forms[form_name];
    var reverse_sort_dir = (formObj.sort_dir.value == 'ASC') ? 'DESC' : 'ASC';
    formObj.sort_dir.value = (formObj.sort_by.value == field) ? reverse_sort_dir : 'ASC';
    formObj.sort_by.value = field;
    formObj.page.value = '1'; // always go back to page 1 upon sort/order
    if( typeof formObj.onsubmit == 'function' )
    { if( formObj.onsubmit() ) { formObj.submit(); return; } }
    else
    { formObj.submit(); }
}

function updateTextBoxURL(textbox,filename) {
	eval("document.getElementById('" + textbox + "').value='" + filename + "'");
}

function updateImageURL(filename,imgwidth,imgheight) {
	var popup = document.getElementById('imgpopwin').value;
	 popwin = window.open("",popup,'alwaysRaised')
	 popwin.document.getElementById('src').value=filename;
	 popwin.document.getElementById('width').value=imgwidth;
	 popwin.document.getElementById('height').value=imgheight;

	popwin.focus();
}
function uploadMCEImages(){
	window.open('http://localhost/wizzit_final/kms/js/tiny_mce/plugins/imagemanager/index.php?type=im','','height=600,width=750,menubar=no');
}
function uploadGalleryMCEImages(){
	window.open('http://localhost/wizzit_final/kms/js/tiny_mce/plugins/imagemanager/index2.php?type=im','','height=600,width=750,menubar=no');
}
/**
 *
 * @access public
 * @return void
 **/
function refreshGallery() {
 var loc = window.location.toString();
 if (loc.search(/gallimg/i) < 1) {
  window.location = window.location + '#gallimg';
 }

 window.location.reload();
}
// window.addEvent('load', User.Init);
window.onload =  User.Init;