var b2 = function() {

	var that = {};
	
	that.saveCropImage = function(h,w,orig,El)
	{
	    Babel.resizeImg($('#x1').val(),$('#y1').val(),$('#x2').val(),$('#y2').val(),w,h,$('#filename').val(), function(res){
	        $(El).val(res.value);
	        $(El).trigger('onblur');
	        $('.imgareaselect-outer').remove();
	        $('.imgareaselect-selection').remove();
	        $('.imgareaselect-border1').remove();
	        $('.imgareaselect-border2').remove();
	        $.nyroModalRemove();
	    });
	    
	};
	
	that.imgUpload = function(width,height,filename,El){
    	$('#uploadPopup').remove();
		$.nyroModalManual({
		  bgColor: '#3333cc',
		  content: Babel.ImgUpload(height,width,filename, El).value,
          endShowContent: function(){
					$('#uploaded_image').html('<img src="'+filename+'" style="float: left; margin-right: 10px; display:block;" id="thumbnail" alt="Create Thumbnail" /><div style="border:1px #e5e5e5 solid; float:left; overflow:hidden; width:' + width + 'px; height:' + height + 'px;display:block;"><img src="'+filename+'" id="thumbnail_preview" alt="Thumbnail Preview" /></div>');
                    var aspect = '1:' + ($("#thumb_height").val() / $("#thumb_width").val());
					$('#thumbnail').imgAreaSelect({ aspectRatio: aspect  , onSelectChange: b2.preview }); 
          }
        });
    
	};
	
	that.uploadImg = function(w,h, El){
	    $.nyroModalManual({
	            bgColor: '#3333cc',
	            content: '<p>Please Select an image to upload</p><iframe id="imgUpFrame" src=default.aspx?Page=uploader&h=' + h+ '&w=' + w + '&el='+El+'></iframe>'
	        });
	    
	};
	
	that.setImgUpload = function()
	{

var myUpload = $('#upload_link').upload({
		   name: 'image',
		   action: '../default.aspx?babel=aaa',
		   enctype: 'multipart/form-data',
		   params: {upload:'Upload'},
		   autoSubmit: true,
		   onSubmit: function() {
		   		$('#upload_status').html('').hide();
				b2.loadingmessage('Please wait, uploading file...', 'show');
		   }
		   ,
           onComplete: function(response) {
           alert(response);
                b2.loadingmessage('', 'hide');   
                response= response.replace(/^\s+|\s+$/g, '');
                var response = unescape(response).split('|');
                var responseType = response[0];
                var responseMsg = response[1];
                if(responseType==='success'){
                    var current_width = response[2];
                    var current_height = response[3];
                    $('#filename').val(responseMsg);
                    $('#upload_status').show().html('<h1>Success</h1><p>The image has been uploaded. Please crop the image to the correct size.</p>');
					$('#uploaded_image').html('<img src="'+responseMsg+'" style="float: left; margin-right: 10px; display:block;" id="thumbnail" alt="Create Thumbnail" /><div style="border:1px #e5e5e5 solid; float:left; overflow:hidden; width:' + $("#thumb_width").val() + 'px; height:' + $("#thumb_height").val() + 'px;display:block;"><img src="'+responseMsg+'" id="thumbnail_preview" alt="Thumbnail Preview" /></div>');
                    var aspect = '1:' + ($("#thumb_height").val() / $("#thumb_width").val());

					$('#thumbnail').imgAreaSelect({ aspectRatio: aspect  , onSelectChange: b2.preview }); 

					$('#thumbnail_form').show();
				}else if(responseType==='error'){
					$('#upload_status').show().html('<h1>Error</h1><p>'+responseMsg+'</p>');
					$('#uploaded_image').html('');
					$('#thumbnail_form').hide();
				}else{
					$('#upload_status').show().html('<h1>Unexpected Error</h1><p>Please try again</p>'+response);
					$('#uploaded_image').html('');
					$('#thumbnail_form').hide();
				}
		   }
		});

	};
	
	that.keyDownHandler = function(btn, evt) {
		evt = evt || event;
		var target = evt.target || evt.srcElement,
			keyCode = evt.keyCode || evt.which;

		if (parseInt(keyCode,10) === 13) {
			// cancel the default event actions
			evt.returnValue = false;
			evt.cancel = true;
			evt.cancelBubble = true;
				
			// submit the form by programmatically clicking the specified button
			document.getElementById(btn).click();
		}
		return false;
	};
	
	that.login = function(uidEl, pwdEl, remMe, redirect)
	{
	    $('#loginErr').html('');

	    LoginControl.Login($(uidEl).val(),pwdEl.val(), remMe, function(res){
	        if (res.value === 'true')
	        {
	            location.href = redirect;
	        }
	        else
	        {
	            $('#loginErr').html('* ' + res.value);
	        }
	    });
	};
	
	that.logout = function(redirect)
	{
	    LoginControl.Logout(function(res){
	        if (res.value === true)
	        {
	            location.href = redirect;
	        }
	        else
	        {
	            alert(res.value);
	        }
	    });
	};
	
that.validate = function(myInput)
    {
        $('#error' + myInput.id).remove();

        var noErr = true;
            var myVal;

			if (myInput.type === 'checkbox') {
				//params[this.id] = this.checked;
				//ignore me, i'll never have validation
			}
			else if (myInput.type === 'select') {
				myVal = myInput.options[myInput.selectedIndex].value;
			}
			else {
				myVal = myInput.value;
			}

            if (typeof $(myInput).attr('valid') !== 'undefined' && myVal !=='')
            {
                var myRegEx;
                //now check the actual value
                switch($(myInput).attr('valid'))
                {
                    case 'email':
                      myRegEx = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$/
                      break;    
                    case 'int':
                      myRegEx = /^(-)?\d*$/
                      break;
                    case 'phone':
                      myRegEx = /^(\+(\d{1,3})(\s)?)?\(?(\d{4,5})\)?\s*(\d{3}(?:-|\s*)\d*)/
                      break;
                    case 'date':
                      myRegEx =/^[0123]?[0-9]\/[01]?[0-9]\/[012][0-9][0-9][0-9](\s[012][0-9]:[0-6][0-9]:[0-6][0-9])?$/  
                      break;
                    case 'postcode':
                    //TODO: this isn't right
                      myRegEx = /^[a-zA-Z]{1,2}[0-9]{1,2}\s?[0-9]{1}[a-zA-Z]{2}$/
                      break;
                    case 'float':
                      myRegEx = /^\d*((\.)(\d){0,2})?$/
                      break;
                    default:
                      myRegEx = $(myInput).attr('valid')
                }

                var patt =new RegExp(myRegEx);
                if (patt.test(myVal) === false)
                {
                    $(myInput).after("<div id='error" + myInput.id + "' class='errorMsg'>* " + $(myInput).attr('err') + "</div>");
 
                    
                    noErr = false; 
                }
            }
            if ($(myInput).attr('req') === 'true')
            {
                if (myVal === '')
                {
                    $(myInput).after("<div id='error" + myInput.id + "' class='errorMsg'>* Required field</div>");
                    noErr = false; 
                }
            }
            
            return noErr;
    };
	

	

	
that.preview = function(img, selection) { 

	//get width and height of the uploaded image.
	var current_width = $('#thumbnail').width();
	var current_height = $('#thumbnail').height();
	
	var scaleX = $('#thumb_width').val() / selection.width; 
	var scaleY = $('#thumb_height').val() / selection.height; 
	
	$('#thumbnail_preview').css({ 
		width: Math.round(scaleX * current_width) + 'px', 
		height: Math.round(scaleY * current_height) + 'px',
		marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px', 
		marginTop: '-' + Math.round(scaleY * selection.y1) + 'px' 
	});
	$('#x1').val(selection.x1);
	$('#y1').val(selection.y1);
	$('#x2').val(selection.x2);
	$('#y2').val(selection.y2);
	$('#w').val(selection.width);
	$('#h').val(selection.height);
};
	
    that.loadingmessage = function(msg, show_hide){
	    if(show_hide=="show"){
		    $('#loader').show();
		    $('#progress').show().text(msg);
		    $('#uploaded_image').html('');
	    }else if(show_hide=="hide"){
		    $('#loader').hide();
		    $('#progress').text('').hide();
	    }else{
		    $('#loader').hide();
		    $('#progress').text('').hide();
		    $('#uploaded_image').html('');
	    }
    };
	
	that.gridClearFilt = function(ctlID)
	{
	    b2.clear('#gridFilt' + ctlID);
	    b2.gridRefresh(ctlID);
	};
	
	that.gridAdd = function(ctlID)
	{
	    b2.saveGroup('#gridNew' + ctlID, 
	        function(){
	            b2.clear('#gridNew' + ctlID);
	            b2.gridRefresh(ctlID);
	        });
	};
	
	that.gridDelete = function(key,ctlID)
	{
	    b2.del(key,
	    	function(){
	            b2.gridRefresh(ctlID);
	        });
	}
	
	that.gridRefresh = function(ctlID)
	{
	    GridControl.Rebuild(ctlID, b2.serialise('#gridFilt' + ctlID,true), function(res){
	        that.upd('control' + ctlID,res.value);
	    });
	};
	
	that.clear = function(elementToGet)
	{
	    $(elementToGet + " input, " + elementToGet + " select, " + elementToGet + " textarea").each(function() {
	        if (this.type !== 'button') {
	            $(this).val('');
	        }
	    });
	};
	
	that.serialise = function(elementToGet, isFilter) {
        var params = {};
        $(elementToGet + " input, " + elementToGet + " select, " + elementToGet + " textarea").each(function() {
            //if (typeof this.babel !== 'undefined' && (isFilter !== true || (isFilter === true && $(this).hasClass('filter'))))
						var ee = $(this).attr('babel');
            if ($(this).attr('babel') !== 'undefined')
            {
			    if (this.type === 'checkbox') {
				    params[$(this).attr('babel')] = this.checked;
			    }
			    else if (this.type === 'select') {
				    params[$(this).attr('babel')] = this.options[this.selectedIndex].value;
			    }
			    else {
			        if (this.type !== 'button') {
				        params[$(this).attr('babel')] = this.value;
				    }
			    }
			}
        });
		
        return JSON.stringify(params);
    };
	
	
	that.del = function(key,fn)
	{
	    Babel.Delete(key, function(res){
	        if (res.value === true)
	        {
	            if (typeof fn === 'function') {
		            fn();
	            }
	        }
	    });
	};
	
	that.saveGroup = function(El,fn)
	{
	    $('#saving').show();
	    var hasErr = false;
	    
        $(El + " input, " + El + " select, " + El + " textarea").each(function() {
            //if (typeof this.babel !== 'undefined' && (isFilter !== true || (isFilter === true && $(this).hasClass('filter'))))
		    if (b2.validate(this) === false)
		    {
		        hasErr=true;
		    }
        });
	    
	    if (hasErr === true)
	    {
	        return false;
	    }
	    
    	var e = b2.serialise(El);
        Babel.SaveGroup(e,false,function(res) {
            
	        if (typeof fn === 'function') {
		        fn(res);
	        }
	        $('#saving').hide('slow');
	    });  

	};
	
    that.save = function(ctl, key, fn)
    {
        //TODO: put in the validation and make a save many (serialise)
        if (b2.validate(ctl) === false)
        {
            return false;
        }
        $('#saving').show();
        var val = ctl.val;
        if (typeof val === 'undefined')
        {
            val = $(ctl).val();

            if (ctl.type === 'checkbox')
            {
                val = ctl.checked;
            }
        }
        var idel = '';
        
        if (typeof ctl.idel !== 'undefined')
        {
            idel = ctl.idel;
            alert($('#' + idel).val());
            Babel.Save(key, val,$('#' + idel).val() ,function(res) {
                if (idel !== '')
                {
                    $('#' + idel).val(res.value);
                }
		        if (typeof fn === 'function') {
			        fn();
		        }
		        $('#saving').hide('slow');
		    }); 
        }
        else
        {
            Babel.Save(key, val,'',function(res) {
                
		        if (typeof fn === 'function') {
			        fn();
		        }
		    });  
		    $('#saving').hide('slow');      
        }
		
    };

//    that.del = function(ctl, fn)
//    {
//        Babel.deleteMe(ctl,function(res) {
//		    if (typeof fn === 'function') {
//			    fn();
//		    }
//		});
//    };

    that.remEl = function(El)
    {
        $('#' + El).remove();
    };

    that.repl = function(El, repWith)
    {
        if (typeof repWith === 'undefined')
        {
            repWith = Babel.refresh(El,'',true).value
        }
        var thisEl=El.split(":");
        if (thisEl.length > 1)
        {
            thisEl = thisEl[1];
        }
        else
        {
            thisEl = thisEl[0];
        }
        $('#' + thisEl).replaceWith(repWith);
    };
    
    that.upd = function(El, repWith)
    {
        if (typeof repWith === 'undefined')
        {
            repWith = Babel.refresh(El,'',false).value;
        }
        var thisEl=El.split(":");
        if (thisEl.length > 1)
        {
            thisEl = thisEl[1];
        }
        else
        {
            thisEl = thisEl[0];
        }
        $('#' + thisEl).html(repWith);
    };

    that.swMode = function()
    {
        Babel.SwitchMode($('#renderMode').val(), function(res){
            if (res.value === true)
            {
               window.location.reload();
            }
        });
    };
    
    that.repCladdTo = function(cl, repCl, addTo)
    {
        $('.' + cl).removeClass(cl).addClass(repCl);
        $('#' + addTo).addClass(cl).removeClass(repCl);
    };
    
    that.hideClshowEl = function(aClass, anEl)
    {
        $('.' + aClass).hide();
        $('#' + anEl).show();
    };
    
    that.filtUpd = function(ElUpd, filtVar,filtSer)
    {
        b2.upd(ElUpd, Babel.refresh(ElUpd,filtVar + ':' + b2.serialise('#' + filtSer,true),true).value);
    };
    
    var myHtmlSettings = {
    nameSpace:       "html", // Useful to prevent multi-instances CSS conflict
    onShiftEnter:    {keepDefault:false, replaceWith:'<br />\n'},
    onCtrlEnter:     {keepDefault:false, openWith:'\n<p>', closeWith:'</p>\n'},
    onTab:           {keepDefault:false, openWith:'     '},
    markupSet:  [
        {name:'Heading 1', key:'1', openWith:'<h1(!( class="[![Class]!]")!)>', closeWith:'</h1>', placeHolder:'Your title here...' },
        {name:'Heading 2', key:'2', openWith:'<h2(!( class="[![Class]!]")!)>', closeWith:'</h2>', placeHolder:'Your title here...' },
        {name:'Heading 3', key:'3', openWith:'<h3(!( class="[![Class]!]")!)>', closeWith:'</h3>', placeHolder:'Your title here...' },
        {name:'Heading 4', key:'4', openWith:'<h4(!( class="[![Class]!]")!)>', closeWith:'</h4>', placeHolder:'Your title here...' },
        {name:'Heading 5', key:'5', openWith:'<h5(!( class="[![Class]!]")!)>', closeWith:'</h5>', placeHolder:'Your title here...' },
        {name:'Heading 6', key:'6', openWith:'<h6(!( class="[![Class]!]")!)>', closeWith:'</h6>', placeHolder:'Your title here...' },
        {name:'Paragraph', openWith:'<p(!( class="[![Class]!]")!)>', closeWith:'</p>'  },
        {separator:'---------------' },
        {name:'Bold', key:'B', openWith:'<strong>', closeWith:'</strong>' },
        {name:'Italic', key:'I', openWith:'<em>', closeWith:'</em>'  },
        {name:'Stroke through', key:'S', openWith:'<del>', closeWith:'</del>' },
        {separator:'---------------' },
        {name:'Ul', openWith:'<ul>\n', closeWith:'</ul>\n' },
        {name:'Ol', openWith:'<ol>\n', closeWith:'</ol>\n' },
        {name:'Li', openWith:'<li>', closeWith:'</li>' },
        {separator:'---------------' },
        {name:'Picture', key:'P', replaceWith:'<img src="[![Source:!:http://]!]" alt="[![Alternative text]!]" />' },
        {name:'Link', key:'L', openWith:'<a href="[![Link:!:http://]!]"(!( title="[![Title]!]")!)>', closeWith:'</a>', placeHolder:'Your text to link...' },
        {separator:'---------------' },
        {name:'Preview', call:'preview', className:'preview' }
    ]
}
    
    that.setMarkup = function()
    {
        $('.markupIn').each(function(index){
            if (!$(this).hasClass('markItUpEditor'))
            {
                $(this).markItUp(myHtmlSettings);
            }
        });

        $('.taSmall').each(function(index){
            if (!$(this).hasClass('markItUpEditor'))
            {
                $(this).markItUp(myHtmlSettings);
            }
        });        
        
    };
    
    that.switchSort = function(table, sortcol){
        //if the col = sortcol, change dir
        if (sortcol === $('#sortCol' + table).val())
        {
            if($('#sortDir' + table).attr('checked') === true)
            {
                $('#sortDir' + table).attr('checked',false);
            }
            else
            {
                $('#sortDir' + table).attr('checked',true);
            }
        }
        else
        //else change
        {
            $('#sortCol'+ table).val(sortcol);
        }
    };
    
    that.switchPerPage = function(table, val){
        $('#perPage'+ table).val(val);
    };
    
    that.switchPage = function(table, val){
        $('#pageNum'+ table).val(val);
    };    
    
    //TODO: put in a clone which clones an elemnt and appends it - increment id & reset oid to -1
    
	return that;
}();


reporting = function() {

	var that = {};
	
	that.addField = function(dsID, path){
	    if ($('#reportFields #' + path).length ===0)
	    {
	        $('#reportFields').append(ReportBuilder.GetField(dsID,path).value);
	    }
	    else
	    {
	        $('.' + path).show();         
	    }
	};
	
	that.addInput = function(dsID, path){
	    var count = $('.' + path).length;
		$('#' + path + (count -1)).after(ReportBuilder.AddInput(dsID,path,count).value);
	};
	
	that.setField = function(path, rowID)
	{
	    $('#' + path + rowID + 'In').val(path + '|' +
	    $('#' + path + rowID + 'Op').val() + '|' +
	    $('#' + path + rowID + 'Fi').val() + '|' +
	    $('#' + path + rowID + 'Va').val());
	};


	
	that.save = function()
	{
	    $('#repID').val(ReportBuilder.Save($('#repID').val(),$('#repDSID').val(),b2.serialise('#reportFields')).value);
	};
	
	
	that.run = function()
	{
	    b2.upd('reportResult',ReportBuilder.Run(b2.serialise('#reportFields')).value);
	};

//javascript:alert(typeof b2.gridRefresh);
	

	
	return that;
}();
