/* +------------------------------------------------------+
 * |                      pPPa                            |
 * |                    pPPAPPp                           |
 * |                   APP  PPa                           |
 * |                  APA  pPP  PapA  PapA                |
 * |                 PPA   APA pP  P pP  P                |
 * |             APPPPPPPA PPp Ap Ap Ap Ap                |
 * |             apPPA    aPP  P     P                    |
 * |              APA     pPP  p     p                    |
 * |             pPP      PPA                             |
 * |             PPp      PPPp                            |
 * |                                                      |
 * | Created by:    App Software                          |
 * | Email:         info@appsoftware.nl                   |
 * | Web:           http://www.appsoftware.nl/            |
 * |                                                      |
 * +------------------------------------------------------+
 * 
 * CMS Main
 * 
 * 
 */

var BART = BART || {};

BART.Front = {};

BART.Front.Util = function() {
	var loadModules = function() {
		BART.Config.modules = [];
		
		Ext.Ajax.request({
        	url : BART.Config.WEB_ROOT+'index.php?cmd=system&action=get_modules',        	
        	success: function(response) {
				var result = Ext.decode(response.responseText);
				
				BART.Config.modules = result.data;
			},
        	failure: function ( result, request) {} 
        }); 
	};
	
    return {
        /**
         * 
         */
        user_attr : {},
        /**
         * 
         */
        init : function() {            
            BART.Front.Util.getUserAttributes();
            
            if(BART.Config && BART.Config.loadModules) {
            	loadModules();
            }
        },
        /**
         * 
         */
        json_call : function(url, postData, onCompletionCallback, onExceptionCallback) {
            var test = Ext.Ajax.request({
            	url : url , 
            	params : postData,
            	method: 'POST',
            	success: onCompletionCallback,
            	failure: (onExceptionCallback ? onExceptionCallback : function ( result, request) { 
            		Ext.MessageBox.alert('Internal server error', result.responseText); 
            	}) 
            });
        },
        /**
         * 
         */
        createCookie : function(name,value,days) {
        	if (days) {
        		var date = new Date();
        		date.setTime(date.getTime()+(days*24*60*60*1000));
        		var expires = "; expires="+date.toGMTString();
        	}
        	else var expires = "";
        	document.cookie = name+"="+value+expires+"; path=/";
        },
        /**
         * 
         */
        readCookie : function(name) {
        	var nameEQ = name + "=";
        	var ca = document.cookie.split(';');
        	for(var i=0;i < ca.length;i++) {
        		var c = ca[i];
        		while (c.charAt(0)==' ') c = c.substring(1,c.length);
        		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        	}
        	return null;
        },
        /**
         * 
         */
        eraseCookie : function(name) {
        	BART.Front.Util.createCookie(name,"",-1);
        },
        /**
         * 
         */
        truncate : function(string, length, truncation) {
        	if (string.length > length) {
        		if (truncation != undefined) {
        			return string.substr(0,length) + truncation;
        		} else {
        			return string.substr(0,length) + '...';
        		}		
        	} else {
        		return string;
        	}
        },
        /**
         * 
         */
        switchStyle : function(styleName) {
        	$('link[rel*=style][title]').each(function(i) {
        		this.disabled = true;
        		if (this.getAttribute('title') == styleName) { 
        		    this.disabled = false;
        		}
        	});
        },
        /**
         * 
         */
        getUserAttributes : function() {
//             BART.Front.Util.json_call('index.php?cmd=ua&action=get',
//                '', 
//                function (response, options) {	   			
//                    if (response) {
//                        BART.Front.Util.user_attr = Ext.util.JSON.decode(response.responseText);
//                    }
//                }
//             );
        },
        /**
         * 
         */
        getUA : function(attr) {
            if (BART.Front.Util.user_attr[attr]) {
                return BART.Front.Util.user_attr[attr];
            }
            return;
        },
        /**
         * 
         */
        setUA : function(attr) {            
            BART.Front.Util.json_call('index.php?cmd=ua&action=edit',
                {attr: Ext.util.JSON.encode(attr)}, function() { return true; }
            );
            return false;
        },
        /**
         * 
         */
        html_entity_decode : function(str) {
            var ta=document.createElement("textarea");
            ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
            
            return ta.value;
        },
        /**
         * 
         */
        setTheme : function(new_theme) {
            try {
           		var body           = Ext.getBody();
           		   		
           		var regexp         = /sfeer[1-6]/;
           		var classname      = body.dom.className;
           		
           		if(regexp.test(classname)) {
           			body.dom.className = classname.replace(regexp, new_theme);   			
           		} else {
         			body.dom.className += ' '+new_theme;
           		} 
           		BART.Front.Util.setUA({theme_id: new_theme});           		
           	} catch(err) {
           	    //alert(err);
           	}
        },
		/**
		 * utf8 encode string
		 * @param {Object} string
		 */
		utf8_encode: function( string ) {
		    // http://kevin.vanzonneveld.net
		    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
		    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		    // +   improved by: sowberry
		    // +    tweaked by: Jack
		    // +   bugfixed by: Onno Marsman
		    // +   improved by: Yves Sucaet
		    // +   bugfixed by: Onno Marsman
		    // *     example 1: utf8_encode('Kevin van Zonneveld');
		    // *     returns 1: 'Kevin van Zonneveld'
		 
		    string = (string+'').replace(/\r\n/g, "\n").replace(/\r/g, "\n");
		 
		    var utftext = "";
		    var start, end;
		    var stringl = 0;
		 
		    start = end = 0;
		    stringl = string.length;
		    for (var n = 0; n < stringl; n++) {
		        var c1 = string.charCodeAt(n);
		        var enc = null;
		 
		        if (c1 < 128) {
		            end++;
		        } else if((c1 > 127) && (c1 < 2048)) {
		            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
		        } else {
		            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
		        }
		        if (enc != null) {
		            if (end > start) {
		                utftext += string.substring(start, end);
		            }
		            utftext += enc;
		            start = end = n+1;
		        }
		    }
		 
		    if (end > start) {
		        utftext += string.substring(start, string.length);
		    }
		 
		    return utftext;
		},
		/**
		 * Create an md5 string
		 * @param {Object} str
		 */
		md5: function(str){
			// http://kevin.vanzonneveld.net
			// +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
			// + namespaced by: Michael White (http://getsprink.com)
			// +    tweaked by: Jack
			// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
			// -    depends on: utf8_encode
			// *     example 1: md5('Kevin van Zonneveld');
			// *     returns 1: '6e658d4bfcb59cc13f96c14450ac40b9'
			
			var RotateLeft = function(lValue, iShiftBits){
				return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
			};
			
			var AddUnsigned = function(lX, lY){
				var lX4, lY4, lX8, lY8, lResult;
				lX8 = (lX & 0x80000000);
				lY8 = (lY & 0x80000000);
				lX4 = (lX & 0x40000000);
				lY4 = (lY & 0x40000000);
				lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
				if (lX4 & lY4) {
					return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
				}
				if (lX4 | lY4) {
					if (lResult & 0x40000000) {
						return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
					}
					else {
						return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
					}
				}
				else {
					return (lResult ^ lX8 ^ lY8);
				}
			};
			
			var F = function(x, y, z){
				return (x & y) | ((~ x) & z);
			};
			var G = function(x, y, z){
				return (x & z) | (y & (~ z));
			};
			var H = function(x, y, z){
				return (x ^ y ^ z);
			};
			var I = function(x, y, z){
				return (y ^ (x | (~ z)));
			};
			
			var FF = function(a, b, c, d, x, s, ac){
				a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
				return AddUnsigned(RotateLeft(a, s), b);
			};
			
			var GG = function(a, b, c, d, x, s, ac){
				a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
				return AddUnsigned(RotateLeft(a, s), b);
			};
			
			var HH = function(a, b, c, d, x, s, ac){
				a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
				return AddUnsigned(RotateLeft(a, s), b);
			};
			
			var II = function(a, b, c, d, x, s, ac){
				a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
				return AddUnsigned(RotateLeft(a, s), b);
			};
			
			var ConvertToWordArray = function(str){
				var lWordCount;
				var lMessageLength = str.length;
				var lNumberOfWords_temp1 = lMessageLength + 8;
				var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
				var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
				var lWordArray = Array(lNumberOfWords - 1);
				var lBytePosition = 0;
				var lByteCount = 0;
				while (lByteCount < lMessageLength) {
					lWordCount = (lByteCount - (lByteCount % 4)) / 4;
					lBytePosition = (lByteCount % 4) * 8;
					lWordArray[lWordCount] = (lWordArray[lWordCount] | (str.charCodeAt(lByteCount) << lBytePosition));
					lByteCount++;
				}
				lWordCount = (lByteCount - (lByteCount % 4)) / 4;
				lBytePosition = (lByteCount % 4) * 8;
				lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
				lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
				lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
				return lWordArray;
			};
			
			var WordToHex = function(lValue){
				var WordToHexValue = "", WordToHexValue_temp = "", lByte, lCount;
				for (lCount = 0; lCount <= 3; lCount++) {
					lByte = (lValue >>> (lCount * 8)) & 255;
					WordToHexValue_temp = "0" + lByte.toString(16);
					WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2);
				}
				return WordToHexValue;
			};
			
			var x = Array();
			var k, AA, BB, CC, DD, a, b, c, d;
			var S11 = 7, S12 = 12, S13 = 17, S14 = 22;
			var S21 = 5, S22 = 9, S23 = 14, S24 = 20;
			var S31 = 4, S32 = 11, S33 = 16, S34 = 23;
			var S41 = 6, S42 = 10, S43 = 15, S44 = 21;
			
			str = BART.Front.Util.utf8_encode(str);
			x = ConvertToWordArray(str);
			a = 0x67452301;
			b = 0xEFCDAB89;
			c = 0x98BADCFE;
			d = 0x10325476;
			
			var xl = x.length;
			for (k = 0; k < xl; k += 16) {
				AA = a;
				BB = b;
				CC = c;
				DD = d;
				a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
				d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
				c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
				b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
				a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
				d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
				c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
				b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
				a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
				d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
				c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
				b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
				a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
				d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
				c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
				b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
				a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
				d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
				c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
				b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
				a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
				d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
				c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
				b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
				a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
				d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
				c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
				b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
				a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
				d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
				c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
				b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
				a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
				d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
				c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
				b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
				a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
				d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
				c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
				b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
				a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
				d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
				c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
				b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
				a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
				d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
				c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
				b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
				a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
				d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
				c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
				b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
				a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
				d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
				c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
				b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
				a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
				d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
				c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
				b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
				a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
				d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
				c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
				b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
				a = AddUnsigned(a, AA);
				b = AddUnsigned(b, BB);
				c = AddUnsigned(c, CC);
				d = AddUnsigned(d, DD);
			}
			
			var temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d);
			
			return temp.toLowerCase();
		},
		/**
		 * 
		 * @param {Object} path
		 * @param {Object} gml
		 * @param {Object} log_to_console
		 */
		gmlvalue: function(path, gml, log_to_console) {
			var mix_value = null;
			
			if (path != null && path.length > 0 && gml != null) {
				var arr_path 			= path.split('.');	//Split on a dot				
				var arr_current_value 	= gml;
				
				/**
				 * log gml array
				 */
				if(log_to_console === true && console != null) {
					console.log(gml);
				}	
				
				var int_pos = 0;
				
				while(int_pos < arr_path.length) {
					if(arr_current_value[arr_path[int_pos]]) {
						arr_current_value = arr_current_value[arr_path[int_pos]];			
					} else if(arr_current_value.waarde != undefined && arr_current_value.waarde[arr_path[int_pos]] != undefined) {
						arr_current_value = arr_current_value.waarde[arr_path[int_pos]];
					} else {
						arr_current_value = null;
						break;
					}
					
					int_pos++;	
				}	
				
				if(arr_current_value != null) {
					if((arr_current_value.constructor.toString().indexOf("Object") > -1) && (arr_current_value.waarde != undefined)) {
						mix_value = arr_current_value.waarde;	
					} else {
						mix_value = arr_current_value;
					}
				} 
				
				return mix_value;				
			} else {
				return null;
			}
		},
		/**
		 * 
		 */
		setRating: function() {
			
			//console.log('hello world');
			return false;
		},
		
		getModuleByInternalName: function(internal_name) {
			var module = null;
			Ext.each(BART.Config.modules, function(mod) {
				if(mod.internal_name == internal_name) {
					module = mod;
					return false;
				}
			});
			
			return module;
		},
		getModuleImageByInternalName: function(internal_name) {
			var module_image = BART.IMG_PATH+'cross.png';
			
			Ext.each(BART.Config.modules, function(mod) {
				if(mod.internal_name == internal_name) {
					module_image = mod.web_dir+mod.image;
					return false;
				}
			});
			
			return module_image;
		},
		newReposNode: function(config) {
			Ext.Ajax.request({
				url: BART.Config.WEB_ROOT+'cms/index.php?cmd=repository&action=new_node_ajax',
				params: { 
					parent_id: config.node_id
				},
				success: function(response) {
					var result = Ext.decode(response.responseText);
	
					if (!result.success || result.exception) {
						Ext.Msg.show({
						   	title		: 'Nieuw item aanmaken',
				   			msg			: 'Er is een fout opgetreden bij het aanmaken van het item.',
				   			buttons		: Ext.Msg.OK,
				   			icon		: Ext.MessageBox.ERROR,
							modal		: true
						});
					} else {
						if(config.success) {
							config.success.call(this, result.data);
						}
					}
				}
			});
		},
		multipleUpload : function(config) {
			if(config == null) {
				config = {};
			}
			
			Ext.Ajax.request({
				url: BART.Config.WEB_ROOT+'index.php?cmd=system&action=session',
				success : function(resp) {
					var result = Ext.decode(resp.responseText);
					var uploaded_files = [];
					
					// Create a new Windows Group for the dialog
					var windowGroup = new Ext.WindowGroup();
					windowGroup.zseed = 13001;
					
					var w = new Ext.Window({
				        title: 'Bestanden toevoegen',
				        width: 400,
				        height: 300,
				        layout: 'fit',
				        closeAction: 'hide',
				        manager: windowGroup,
				    	modal: true,
				        items: [
							new Ext.ux.SwfUploadPanel({
					            border: false,
					            debug: false,				
					            upload_url: BART.Config.WEB_ROOT+'index.php?cmd=repository&action=multiple_upload',
					            post_params: {
					                sid: result,
									node_id: config.node_id || 1
					            },
					            file_types: config.file_types || '*.*',
					            file_types_description: config.file_types_description || 'Alle bestanden',
					            flash_url: '/external/ext-ux/ux/swfupload/swfupload.swf',
								strings: {
							        text_add: 'Voeg bestand toe',
							        text_upload: 'Verwerk lijst',
							        text_cancel: 'Cancel Upload',
							        text_clear: 'Lijst leeghalen',
							        text_progressbar: 'Voortgang',
							        text_remove: 'Verwijder bestand',
							        text_remove_sure: 'Weet je zeker dat je dit bestand van de lijst wilt verwijderen?',
							        text_error: 'Error',
							        text_uploading: 'Bezig met uploaden: {0} ({1} of {2})',
							        header_filename: 'Bestandsnaam',
							        header_size: 'Omvang',
							        header_status: 'Status',
							        status: {
							            0: 'Wachten',
							            1: 'Uploaden...',
							            2: 'Voltooid',
							            3: 'Error',
							            4: 'Geannuleerd'
							        },
							        error_queue_exceeded: 'The selected file(s) exceed(s) the maximum number of {0} queued files.',
							        error_queue_slots_0: 'There is no slot left',
							        error_queue_slots_1: 'There is only one slot left',
							        error_queue_slots_2: 'There are only {0} slots left',
							        error_size_exceeded: 'The selected files size exceeds the allowed limit of {0}.',
							        error_zero_byte_file: 'Zero byte file selected.',
							        error_invalid_filetype: 'Invalid filetype selected.',
							        error_file_not_found: 'File not found 404.',
							        error_security_error: 'Security Error. Not allowed to post to different url.'
							    },
					            // Set to true if you only want to select one file from the FileDialog.
					            single_file_select: false, 
					            
								// This will prompt for removing files from queue.
					            confirm_delete: true, 
								
					            // Remove file from grid after uploaded.
					            remove_completed: true,
					            
					            listeners: {
					                startUpload: function(panel) {
					                    // called when upload starts										
					                },
									fileUploadSuccess: function(g, f, d) {
										uploaded_files.push(d.data);
									},
					                allUploadsComplete: function(g) {					                    
										if (config.success) {
											config.success.call(this, uploaded_files);
										}			
																																					
										uploaded_files = [];
										
										if(config.close_after_uploads_complete) {
											w.close();
										}
					                }
					            }
					        })
						]
					});
					w.show();
				}
			});
		}
    };   
}();

//BART.Front.Util.init();


$(document).ready(function() { 
	$('.mod_external_content iframe').attr('ALLOWTRANSPARANCY');
});