var siteURL = "http://" + location.hostname;
var baseUrl = "";

var loadJS = {
	load: function (scriptLocation) {
	    var scr = document.createElement('script');
		scr.setAttribute('type', 'text/javascript');
		scr.setAttribute('language', 'JavaScript');
		scr.setAttribute('src', scriptLocation);
		document.getElementsByTagName('HEAD')[0].appendChild(scr);
	    return;
	}
}

var Size = {
	/**
	 * Get screen size
	 */
	screenSize: function () {
    	var width, height;
    	//width = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
    	height = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
		
		//height = $("body").height(); // works incorrect 
		width = $("body").width();
    	return {w:width, h:height};
	},
	/**
	 * Get position scroll
	 */
	getPageScroll: function() {
	    var xScroll, yScroll;
	    if (self.pageYOffset) {
	    	yScroll = self.pageYOffset;
	    	xScroll = self.pageXOffset;
	    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
	    	yScroll = document.documentElement.scrollTop;
	    	xScroll = document.documentElement.scrollLeft;
	    } else if (document.body) {// all other Explorers
	    	yScroll = document.body.scrollTop;
	    	xScroll = document.body.scrollLeft;	
	    }
	    return {x:xScroll, y:yScroll};
    },
	/**
	 * Get size element
	 * @param {String} idElement
	 */
	getSizeElement: function (idElement) {
		var height, width; 
		if (document.getElementById(idElement)) {
			height = $("#" + idElement).height(); 
			width = $("#" + idElement).width();
		} 
		return {w:width, h:height};
	}
}

var Preload = {
	activePreload: true,
	smallImg: false,
	imgLoadingBig: '<img id="preloadImg" src="/images/loading.gif" />',
	imgLoadingSmall: 'Small image not exist',
	
	/**
	 * Switch image loading
	 */
	switchLoadImg: function () {
		return (this.smallImg == true) ? this.imgLoadingSmall : this.imgLoadingBig;
	},
	/**
	 * Create effect loading for one element
	 * @param {String} id
	 */
	runOneLoading: function (id) {
		if (document.getElementById(id)) {
			var imgLoading = Preload.switchLoadImg();
			var posElem = $("#" + id).offset();
			var sizeElem = Size.getSizeElement(id);
			var topOff = (sizeElem.h / 2) + posElem.top - 16;
			var leftOff = (sizeElem.w / 2) + posElem.left - 16;
			
			var div = jQuery('<div>' + imgLoading + '</div>').addClass('loading').attr('id', 'one-loading-' + id);
			div.css({
				top: topOff,
				left: leftOff,
				position: "absolute",
				display: "none"
			});
			
			$("#" + id).append(div);
			$("#one-loading-" + id).fadeIn(200);
		}
	},
	/**
	 * Destroy effect loading for one element
	 */
	stopOneLoading: function (id) {
		if (document.getElementById(id)) {
			$("#" + id).find("#one-loading-" + id).remove();
		}	
	},
	/**
	 * Run effect loading for one element
	 * @param {String} id
	 */
	standartOneLoading: function (id) {
		$(document).ready(function () {
			if (Preload.activePreload) {
				if (document.getElementById("one-loading-" + id)) {
					Preload.stopOneLoading(id);
				} else {
					Preload.runOneLoading(id);
				}
			}
		});
	},
	/**
	 * Create loading element of page
	 */
	runLoading: function () {
		var imgLoading = Preload.switchLoadImg();
		
		var scrol = Size.getPageScroll();
		var param = Size.screenSize();
		var topOff = ((param.h / 2) - 16) + scrol.y;
		var leftOff =((param.w / 2) - 16) + scrol.x;

		var div = jQuery('<div>' + imgLoading + '</div>').addClass('loading').attr('id', 'layer-loading');
		div.appendTo(document.body);
		div.css({
			zIndex: Boxy._nextZ(),//так как юзаем боксы
			top: topOff,
			left: leftOff,
			position: "absolute"
		});
		
		$("#layer-loading").fadeIn("fast");
	},
	/**
	 * Destroy loading element
	 */
	stopLoading: function () {
		$("#layer-loading").remove();
		//runRounded();

	},
	/**
	 * Run standart preloader
	 */
	standartPreload: function () {
		$(document).ready(function () {
			if (Preload.activePreload) {
				if (document.getElementById("layer-loading")) {
					Preload.stopLoading();
				} else {
					Preload.runLoading();
				}
			}
		});
	},
	/**
	 * Run effect loading for Ajax
	 */
	ajaxRunPreload: function (id) {
		$(document).ready(function () {
			if (Preload.activePreload) {
				$("#" + id).ajaxStart(function () {
					Preload.runLoading();
				});				
				$("#" + id).ajaxSuccess(function (evt, request, settings) {
				 	Preload.stopLoading();
				});	
			}
		});
	}
}

var Utilit = {
	displayResponse: true,
	
	/**
	 * Show request
	 * @param {Object} formData
	 * @param {Object} jqForm
	 * @param {Object} options
	 */
	showRequest: function (formData, jqForm, options) { 
    	var queryString = $.param(formData); 
    	return true; 
	},
	/**
	 * Query ajax form
	 * @param {String} idForm
	 * @param {String} queryUrl
	 * @param {String} idUpdate
	 */
	queryAjaxForm: function (optionsFunc) {
		//optionsFunc : idForm, url, idUpdate, typeAjax, proccessFunction, reload, emptyId
		if (optionsFunc == undefined) {
			optionsFunc = {};
		}	
		if (optionsFunc.proccessFunction == undefined) {
			optionsFunc.proccessFunction = function() {};
		}	
		$(document).ready(function () {
			var options = {
				url: optionsFunc.url,
				type: "POST",
				dataType: 'json',
				beforeSubmit: function (formData, jqForm, options) { 
			    	Preload.standartPreload();
				},
				success: function(responseText, statusText) {
					if (statusText == "success") {
						Preload.standartPreload();
							
						Message.parse(optionsFunc.idForm, responseText);
							
						if (typeof Utilit.displayResponse == false) {
							return responseText.response; 
						} else {
							if ((optionsFunc.idUpdate != "") && ($('#' + optionsFunc.idUpdate).length > 0)) {
								$("#" + optionsFunc.idUpdate).html(responseText.response);
								if (responseText.typeMsg != 'error') {
									if (optionsFunc.emptyId != undefined) {
										$('#' + optionsFunc.emptyId).empty();
									}
									optionsFunc.proccessFunction();
								}								
							}
							if (optionsFunc.reload && optionsFunc.idUpdate) {
								Utilit.getUrl(optionsFunc.idUpdate, optionsFunc.queryUrl);	
							}
						}
					}
				}
			};
			if (optionsFunc.typeAjax == 'submit') {
				$('#' + optionsFunc.idForm).ajaxSubmit(options);	
			} else {
				$('#' + optionsFunc.idForm).ajaxForm(options);	
			}
		});
	},
	/**
	 * Ajax query only one element
	 * @param {String} idElem
	 * @param {String} queryUrl
	 * @param {String} data
	 * @param {String} idUpdate
	 */
	ajaxOneElement: function (idElem, queryUrl, data, idUpdate) {
		$(document).ready(function () {
			var elemData = $("#" + idElem).serialize();
			if (typeof data == "string") {
				if (data != "") {
					var sepParam = (data.substr(0, 1) != "&") ? "&" : ""; 				
					elemData += (sepParam + data);	
				}
			}
			var options = {
				url: queryUrl, 
				type: "POST",
				data: elemData,
				dataType: "json",
				beforeSend: function () {
					Preload.standartPreload();
				},
				success: function(responseText, statusText) {
					if (statusText == "success") {
						Preload.standartPreload();

						Message.parse(idElem, responseText, "element");
						if (idUpdate != "") {
							$("#" + idElem).val(responseText.response);
						}
					}
				}
			};
			jQuery.ajax(options);
		});
	},
	
	visibleElem: function (id, statUp) {
		$(document).ready(function () {
			if (document.getElementById(id)) {
				var stat = $("#" + id).css("display");
				if ("none" == stat) {
					$("#" + id).slideDown("normal");	
				} else {
					if (statUp == "up") {
						$("#" + id).slideUp("normal");	
					}
				}
			}	
		});
	},
	
	ajaxDelete: function (params, queryUrl, idUpdate) {
		$(document).ready(function () {
			var options = {
				url: queryUrl,
				type: "POST",
				dataType: 'json',
				data: params,
				beforeSend: function () {
					Preload.standartPreload();
				},
				success: function(responseText, statusText) {
					if (statusText == "success") {
						Preload.standartPreload();
						Message.message(responseText);
						if (idUpdate != "") {
							if (responseText.response){
								$("#" + idUpdate).html(responseText.response);	
							} else {
								$("#" + idUpdate).empty();
							}
						}
					}
				}
			};
			jQuery.ajax(options);
		});
	},
	ajaxDeleteHtml: function (params, queryUrl, idUpdate) {
		$(document).ready(function () {
			var options = {
				url: queryUrl,
				type: "POST",
				dataType: 'html',
				data: params,
				beforeSend: function () {
					Preload.standartPreload();
				},
				success: function(responseText, statusText) {
					if (statusText == "success") {
						Preload.standartPreload();
						Message.message(responseText);
						if (idUpdate != "") {
							if (responseText.response){
								$("#" + idUpdate).html(responseText.response);	
							} else {
								$("#" + idUpdate).empty();
							}
						}
					}
				}
			};
			jQuery.ajax(options);
		});
	},
	cancelForm: function (idForm, disp) {
		$(document).ready(function () {
			if (document.getElementById(idForm)) {
				$("#" + idForm).clearForm();
				//$("#" + idForm).resetForm();
				if (disp == "hide") {
					$("#" + idForm).slideUp("normal");	
				}
			}
		});
	},
	
    centerElement: function(id){
        var w = $(window);
        var elem = $('#' + id);
        elem.css("position", "absolute");
        elem.css("top", (w.height() - elem.height()) / 2 + w.scrollTop() + "px");
        elem.css("left", (w.width() - elem.width()) / 2 + w.scrollLeft() + "px");
        return true;
    },
	
	emptyValueHidden: function (idForm) {
		$(document).ready(function () {
			$("#" + idForm + " :input[type='hidden']").each(function(index, domEle) {
				$(domEle).val("");
			});
		});
	},
	
	createDialog: function(idElem, contentDialog, titleDialog, textButtonOk, funcOk, textButtonCancel) {
		$(document).ready(function() {
			if (document.getElementById(idElem)) {
				$('#' + idElem).dialog('open');
			} else {
				var div = jQuery('<div>' + contentDialog + '</div>').attr('id', idElem);
				div.appendTo(document.body);
				div.css({
					display: "none"
				});
				
				$('#' + idElem).dialog({
					modal: true,
					resizable: false,
					position: ['center', 'center'],
					title: (titleDialog != "") ? titleDialog : "&nbsp;",
					buttons: {
						"Ok": function() {
							if (funcOk != "") {
								eval(funcOk);
							}
							$(this).dialog('close');
						},
						"Cancel": function() {
							$(this).dialog('close');
						}
					}
				}).css({
					display: "block"
				});
				
				if (textButtonOk != "") {
					$(".ui-dialog-buttonpane button:eq(0)").html(textButtonOk);
				}
				if (textButtonCancel != "") {
					$(".ui-dialog-buttonpane button:eq(1)").html(textButtonCancel);
				}
			}
		});
	},
	
	contentMce : function(elementId) {
		$('#' + elementId).val(tinyMCE.get(elementId).getContent());
	}
}

var Message = {
	visualEffect: true,
	errorSelector: "div.error",
	dialogFooter: false,
	
	/**
	 * Process selector
	 * @param {String} id
	 * @param {String} typeElem
	 */
	processSelector: function (id, typeElem) {
		var selector = (typeElem == "element") ? ("#error_" + id) : ("#" + id + " " + Message.errorSelector);
		$(selector).slideUp("fast", function () {
			$(selector).remove();
		});
	},
	/**
	 * Set errors for one element
	 * @param {String} idElem
	 * @param {Object} jsonData
	 * @param {String} typeElem
	 */
	errorElem: function (idElem, jsonData, typeElem) {
		$(document).ready(function () {
			Message.processSelector(idElem, typeElem);
			
			for (var i in jsonData.data) {
				if ($("#" + idElem).is(":input[name='"+ i + "']")) {
					$("#" + idElem).before($("<div id='error_" + idElem + "' class='error'>" + jsonData.data[i] + "</div>"));
			 	}
			}
		});
	},
	/**
	 * Set errors for form
	 * @param {String} idForm
	 * @param {Object} jsonData
	 */
	error: function (idForm, jsonData) {
		$(document).ready(function () {
			var selector = "#" + idForm + " " + Message.errorSelector;
			$(selector).remove();

			for (var i in jsonData.data) {
				$("#" + idForm + " :input:not(:submit)").each(function (index, domEle) {
					if ($(this).is(":input[name='"+ i + "']")) {
						$(this).before($("<div class='error'>" + jsonData.data[i] + "</div>"));
						//разукрасим импуты 
						if($(this).hasClass("register_input")) {
							$(this).css({
								border: '1px solid #FA1D0B',
								background: 'url(/images/input_valid_error.gif) no-repeat right'
							});
						}
				 	}
				});
			}
		});
	},
	/**
	 * Set message
	 * @param {String} idForm
	 * @param {Object} jsonData
	 * @param {String} typeElem
	 */
	setMessage: function (idForm, jsonData, typeElem) {
		$(document).ready(function () {
			Message.processSelector(idForm, typeElem);
			Message.message(jsonData);
		});
	},
	/**
	 * Create obj. message
	 * @param {Object} jsonData
	 */
	message: function (jsonData, duration) {
		$(document).ready(function () {
			try {
				duration = duration || 2500;
				var content = "";
				for (var i in jsonData.data) {
					content += "<div class='message'>" + jsonData.data[i] + "</div>";
				}
				
				jQuery.facebox.settings.close_image = '/styles/facebox/closelabel.gif';
				jQuery.facebox(function () {
					if (Message.dialogFooter == false) {
						$('#facebox .footer').remove();	
					}
					var topOff = 0;
					var leftOff = 0;
					var widthElement = 410;
					
					var scrol = Size.getPageScroll();
					var param = Size.screenSize();
					
					var topOff = scrol.y;
					var leftOff =((param.w / 2) - (widthElement / 2)) + scrol.x;
	
					$("#facebox").css({
						top: topOff,
						left: leftOff,
						width: widthElement,
						position: "absolute"
					});
					
					jQuery.facebox($(content));
					setTimeout("jQuery.facebox.close()", duration);
					
					return ;
				});
			} catch (e) {
				alert(e);
			}
		});
	},
	/**
	 * Parse response query
	 * @param {String} idForm
	 * @param {Object} jData
	 * @param {String} typeElem
	 */
	parse: function (idForm, jData, typeElem) {
		$(document).ready(function () {
			try {
				switch (jData.typeMsg) {
					case "error":
					(typeElem == "element") ? Message.errorElem(idForm, jData, typeElem) : Message.error(idForm, jData);
					break;
					
					case "message":
					Message.setMessage(idForm, jData, typeElem);
					try {
						$('#' + idForm).resetForm();	
					} catch (e) {}
					break;
					
					case "redirect":
					location.href = jData.redirect;
					break;
					
					default:
					Message.processSelector(idForm, typeElem);
					try {
						$('#' + idForm).resetForm();	
					} catch (e) {}
					break;
				}
			} catch (e) {
				alert("Exception: " + e);
			}
		});
	},
	
	simpleMessage: function (msg, duration) {
		$(document).ready(function () {
			try {
				duration = duration || 2500;
				data = "<div class='message'>" + msg + "</div>";
				jQuery.facebox($(data));
				setTimeout("jQuery.facebox.close()", duration);
			} catch (e) {
				alert("Exception: " + e);
			}
		});
	}
}

var Calendar = {
	
	/**
	 * Synchronise two datepickers to together select a date range.
	 * @param {String} idStartDate
	 * @param {String} idEndDate
	 */
	createRange: function (idStartDate, idEndDate) {
		$(document).ready(function () {
			$("#" + idStartDate + ",#" + idEndDate).datepicker($.extend({}, 
				$.datepicker.regional['ru'], {
					yearRange: "-1:+10",
					changeFirstDay: false,
				    beforeShow: customRange,
					dateFormat: 'dd.mm.yy',
					showOn: "both",     
					buttonImage: "/images/calendar.jpg",
					buttonImageOnly: true,
					nextText: '',
					prevText: ''
				})
			).attr("readonly", "readonly"); 
		
			function customRange(input) { 
			    return {
			    	minDate: (input.id == idEndDate ? $("#" + idStartDate).datepicker("getDate") : null), 
			        maxDate: (input.id == idStartDate ? $("#" + idEndDate).datepicker("getDate") : null)
			    }; 
			}
		});
	},
	/**
	 * Create basic calendar
	 * @param {String} idDate
	 */
	create: function (idDate) {
		$(document).ready(function () {
			$("#" + idDate).datepicker($.extend({}, 
				$.datepicker.regional["ru"], { 
					yearRange: "-1:+5",
					changeFirstDay: false,
					dateFormat: 'dd.mm.yy',
					showOn: "both",
					buttonImage: "/images/calendar.jpg",
					buttonImageOnly: true
				})
			).attr("readonly", "readonly");
		});
	}
}

var Style = {
	
	/**
	 * Change style (class) for element
	 * @param {Object} elem
	 * @param {String} nameClass
	 */
	changeOverOut: function (elem, nameClass) {
		$(document).ready(function () {
	      	$(elem).addClass(nameClass);
			$(elem).mouseout(function () {
			      $(this).removeClass(nameClass);
			    }
			);
		});
	}
}

var Contents = {	
	moreInformation: function (idElem, idContent) {
		$("#" + idElem).load("/index/get-content/content_id/" + idContent);
	},	
	getLocalProfile: function (idUpdate, idCompany) {
		$("#" + idUpdate).load('/company-profiles/get-local-profile/company/' + idCompany);
	}
}

var Box = {
		/**
		 * Create dialog for messages
		 * @param {Object} optionsFunc
		 */
		msgDialog: function(optionsFunc) {
			// title, id, content
			if (optionsFunc == undefined) {
				optionsFunc = {};
			}
			$(document).ready(function () {
				sendArticle.remove();
				if ((boxyFind.length == 0) || (boxyFind.is(':hidden'))) {
					if (boxyFind.is(':hidden')) {
						boxyFind.remove();
					}				
					if (optionsFunc.title != undefined) {
						Boxy.DEFAULTS.title = optionsFunc.title;
					}
					var options = {
						id: optionsFunc.id,
						center: true,
						hide: false, 
						fixed: true,
						closeable: false,									
						draggable: false,
						modal: false,
						afterShow: function() {
							this.moveToY(0);
						}
					};
					if (optionsFunc.content != 0) {								
						new Boxy(optionsFunc.content, options);
					}
					return false;
				}
			});
		},
		/**
		 * Create content in the dialog
		 * @param {Object} optionsFunc
		 */
		dialog: function (optionsFunc) {
			// optionsFunc: obj, url, params, title, type, id, closeable, center, proccessFunction
			if (optionsFunc == undefined) {
				optionsFunc = {};
			}				
			$(document).ready(function () {
				Preload.standartPreload();
				var boxyFind = $('#boxy_id_' + optionsFunc.id);
				if ((boxyFind.length == 0) || (boxyFind.is(':hidden'))) {
					if (boxyFind.is(':hidden')) {
						boxyFind.remove();
					}				
					var options = {
						url: optionsFunc.url,
						type: "POST",
						data: optionsFunc.params,
						dataType: "html",
						success: function (responseText, statusText) {
							if (statusText == "success") {
								// Dialog
								if (optionsFunc.type == 'modal') {
									var options = {
										id: optionsFunc.id,
										center: true,
										fixed: true,
										modal: true,
										clone: true,
										closeable: false,
										afterShow: function () {
											Preload.standartPreload();
											if (optionsFunc.proccessFunction != undefined) {											
												optionsFunc.proccessFunction();
											}
											if (optionsFunc.staticPos) {
												var posElem = $('#boxy_id_' + optionsFunc.id).offset();
												this.moveTo(posElem.left, 22);
											}
										}
									};
								} else {
									var posElem = $(optionsFunc.obj).offset();
									var height = $(optionsFunc.obj).height();
									var options = {
										id: optionsFunc.id,
										center: false,
										fixed: false,
										closeable: true,									
										draggable: true,
										modal: false,
										afterShow: function () {
											this.moveTo(posElem.left, posElem.top + height);
										}
									};
								}
								if (optionsFunc.center != undefined) {
									options.center = optionsFunc.center;
									options.afterShow = function () {}
								}
								if (optionsFunc.title != undefined) {
									options.title = optionsFunc.title;								
								}
								if (optionsFunc.closeable != undefined) {
									options.closeable = optionsFunc.closeable;
								}
								if (responseText.length != 0) {
									new Boxy(responseText, options);
								}						
							}
						}
					};
					jQuery.ajax(options);
					return false;
				}
			});
		},
		/**
		 * Process form for dialog
		 * @param {Object} obj
		 * @param {String} urlAction
		 * @param {String} idForm
		 * @param {String} idUpdate
		 */
		dialogForm: function (obj, urlAction, idForm, idUpdate) {
			$(document).ready(function () {
				var options = {
					url: urlAction,
					type: 'POST',
					dataType: 'json',
					success: function(responseText, statusText) {					
						if (statusText == "success") {								
							if (responseText.typeMsg != 'error'){
								if (idUpdate != '') {
									$('#' + idUpdate).html(responseText.response);
								}
								Boxy.get(obj).hide();								
							} 
							try {
								setTimeout(Message.parse(idForm, responseText), '1500');		
							} catch (e) {}
						}
						return false;
					}
				};
				$('#' + idForm).ajaxSubmit(options);
			});
		}
	}

