jQuery.easing.def = "jswing";

var externalParams = getQueryParams('script');
var pathWeb = externalParams.pathWeb;

function notThatFast(e)
{
	alert('В данный момент эта функция недоступна. Приносим свои извинения.');
	return false;
}

function temporaryLocked(e)
{
	alert('В данный момент эта функция отключена. Приносим свои извинения.');
	return false;
}


function log(msg)
{
	if(typeof(console) != "undefined") {
		console.log(msg);
	}
}

$(function(){
	/**
	* JS Links
	**/
	$('a.jsLink').live('click', function(e){
	e.preventDefault();
	});
	
	
	/**
	* Hover changing images
	**/	
	$('img.hoverchange').mouseover(function(){
		changeImgSrc($(this));
	});
	
	$('img.hoverchange').mouseout(function(){
		changeImgSrc($(this));
	});
	

	$('img.hoverchange.gifs.presschange').mousedown(function(){
		changeImgSrcMouseDown($(this));
	});	
	$('img.hoverchange.gifs.presschange').mouseup(function(){
		changeImgSrcMouseDown($(this));
	});	
	
	$(".tip").tooltip(
		{
			track: true,
			showURL: false,
			positionLeft: true,
			showBody : false,
			delay : 500
		}
	); 	
	
	$cartTop = $('div.cart');
	$errorDiv = $('<div class="item-popup-error"></div>');

	
	/**
	* Catalog
	*/
	
	
	$('a.add2cart').live('click', function(e){

		$target = $(e.target);
		
		if(!inputValidation($target)) {
			return false;
		}		
		
		if($target.is('img')) {
			$target = $target.parents('a:first');
		}
		
		$qInput = $target.parents('li:first').find('input[type=text]');
		
		callback = $target.hasClass('add2cartZoom') ? add2cartZoomCallback : add2cartCallback;

		/* Visual */
		$target.parents('div:first').hide();
		$target.parents('li:first').find('div.adding-to-cart').show();
		
		
		$.post(
			pathWeb+'?area=partnerCatalogController',
			{action : 'addcartitem', pTag : $target.chunkId(), quantity: $qInput.val()},
			callback,
			'json'
		);
	});	

//	$('div.catalog-items-list ul li input').blur(function(e){
//		if(!inputValidation(e)) {
//			return false;
//		}
//	});	

	/**
	* UniSender
	**/
	$('#us_form').find('input[type=text]').each(function(){
		$(this).val($(this).attr('title'));
	});
	
	$('#us_form').find('input[type=text]').focus(function(){
		if($(this).val() == $(this).attr('title')) {
			$(this).val('');
		}
	});
	
	$('#us_form').find('input[type=text]').blur(function(){
		if($(this).val() == '') {
			$(this).val($(this).attr('title'));
		}
	});
	
	
	/**
	* AJAX file upload  for Q&A edit
	**/
	function qaFileUpload($formWrapper)
	{
		
		var $fileField = $formWrapper.find('input.fileField');
		var type = $formWrapper.hasClass('questionSetEditFormWrapperQuestion') ? 'q' : 'a';
		var contentId = $formWrapper.attr('contentId');

		
		$formWrapper.find('div.file-upload-block').hide();
		$formWrapper.find('div.file-loading-block').show();
		$formWrapper.find('div.file-error-block').hide();
		$.ajaxFileUpload
		(
			{
				url:pathWeb + '?area=CMSContentTypeControllerQuestionSet&action=uploadFile&type=' + type + '&id=' + contentId,
				secureuri:false,
				fileElementId:$fileField.attr('id'),
				dataType: 'json',
				success: function (data, status)
				{
					$formWrapper.find('div.file-upload-block').show();
					$formWrapper.find('div.file-loading-block').hide();
					if(typeof(data.error) != 'undefined')
					{
						if(data.error != '')
						{
							$formWrapper.find('div.file-error-block').show();
						}else
						{
							$formWrapper.find('div.file-error-block').hide();
							$formWrapper.find('div.file-link-block').show();
							$formWrapper.find('div.file-link-block').find('a.file-link').attr('href', data.filelink);
						}
					}
				},
				error: function (data, status, e)
				{
					alert(e);
				}
			}
		)
		
		return false;

	}	
	
	
	$('div.questionSetEditFormWrapper').find('input.fileSubmit').live('click', function(){
		var $formWrapper = $(this).parents('div.questionSetEditFormWrapper:first');
		qaFileUpload($formWrapper);
	});
	
	$('div.questionSetEditFormWrapper').find('.file-link-block a.remove-file').live('click', function(){
		
		var $formWrapper = $(this).parents('div.questionSetEditFormWrapper:first');
		var type = $formWrapper.hasClass('questionSetEditFormWrapperQuestion') ? 'q' : 'a';
		var contentId = $formWrapper.attr('contentId');		
		
		$.get(
			pathWeb + '?area=CMSContentTypeControllerQuestionSet&action=dropFile&type=' + type + '&id=' + contentId,
			function(response) {
				
			}
		);
		$formWrapper.find('div.file-link-block').hide();
	});
});



function inputValidation($target)
{
	$li = $target.parents('li:first');
	$input = $li.find('input');
	
	mult = $input.chunkId();
	
	
	val = parseInt($input.val());
	
	if(val == 0 || val % mult || isNaN(val) || isNaN(val & mult)) {
		if(isNaN(val)) {
			val = mult;
		}
		var newVal = mult;	
		
		if(val <= mult) {
			newVal = mult;
		}
		else {
			newVal = val + (mult - (val % mult) ) ;
		}
		
		$errorDiv.html('Количество должно <br> быть кратно <b>'+mult+'</b>');	
		
		$li.append($errorDiv);
		$errorDiv.stop().show().css('opacity', 1).animate({opacity : 0}, 3000, function() {$errorDiv.hide()});
		
		setTimeout(function() {$input.focus().select();}, 100);
		
		
	}
	
	$input.val(typeof(newVal) != "undefined" ? newVal : val);	
	
	return typeof(newVal) == "undefined";
}

function add2cartCallback(response) 
{
	if(response.cartItemsCount && response.cartSum) {
		$cartTop.find('div.cart-content span.cart-count').html(response.cartItemsCount);
		$cartTop.find('div.cart-content span.cart-sum').html(response.cartSum+'руб');
		
		if(!$cartTop.find('div.cart-content').is(':visible')) {
			$cartTop.find('div.cart-content').show();
			$cartTop.find('.empty').hide();
		}
	}
	
	$target.parents('li:first').find('div.adding-to-cart').hide();
	$target.parents('li:first').find('div.added-to-cart').fadeIn(300);
}

function add2cartZoomCallback(response) 
{
	if(response.cartItemsCount && response.cartSum) {
		$cartTop.find('div.cart-content span.cart-count').html(response.cartItemsCount);
		$cartTop.find('div.cart-content span.cart-sum').html(response.cartSum+'р');
	}
	$target.parent('div:first').siblings('div.added-to-cart').fadeIn(300);
	$target.parent('div:first').hide();
}	



function changeImgSrcMouseDown($img)
{
	imgExt = 'gif';
	oldSrc = $img.attr('src');
	newSrc = oldSrc.substr(0, oldSrc.length-4);
	newSrc = newSrc.replace('_hover', '');
	if($img.hasClass('pressing')) {
		//newSrc = newSrc.replace('_press', '');
		//$img.removeClass('pressing');
	}
	else {
		$img.addClass('pressing');
		newSrc = newSrc+'_press';
	}
	$img.attr('src', newSrc+'.'+imgExt);	
}

function changeImgSrc($img)
{
	if(strpos($img.attr('src'), 'transparent') !== false) {
		return;
	}
	imgExt = 'gif';
	oldSrc = $img.attr('src');
	newSrc = oldSrc.substr(0, oldSrc.length-4);


	if($img.hasClass('hovering')) {
		if($img.hasClass('gifs')) {
			newSrc = newSrc.replace('_hover', '');
		}
		else {
			imgExt = 'png';
		}
		$img.removeClass('hovering');
	}
	else {
		$img.addClass('hovering');
		if($img.hasClass('gifs')) {
			newSrc = newSrc+'_hover';
		}		
	}
	$img.attr('src', newSrc+'.'+imgExt);	
	//alert($img.attr('src'));
}

function confirm_drop(msg)
{
	if(msg)
		return confirm('Удалить '+msg+'?');	
	else
		return confirm('Удалить объект?');		
}

function confirmDrop(msg)
{
	if(msg)
		return confirm('Удалить '+msg+'?');	
	else
		return confirm('Удалить объект?');		
}

function confirmMes(msg)
{
	if(msg)
		return confirm(msg);	
	else
		return confirm('Выполнить действие?');		
}

function getQueryParams(scriptId) {
	scriptId = (typeof(scriptId) == "undefined") ? 'external' : scriptId;
	externalParams = new Object;
	
	$scriptTag = $('#'+scriptId);
	
	
	if(!$scriptTag.size())
		return externalParams;
	
	src = $scriptTag.attr('src');
	tmp = src.split('?');
	
	if(typeof(tmp[1]) != "undefined") {
		params = tmp[1].split(/[;&]/);
		for(var iep=0; iep < params.length; iep++) {
			varData = params[iep].split('=');
			externalParams[varData[0]] = varData[1];
		}
	}
	return externalParams;

}


/**
* UniSender
**/
var us_msg = {missing: "Не задано обязательное поле: \"%s\"", invalid: "Недопустимое значение поля: \"%s\"", email_or_phone: "Не задан ни email, ни телефон", no_list_ids: "Не выбрано ни одного списка рассылки"};
function us_onLoadImpl() {
	us_autodetectCharset();
}
var us_onLoadOld = null;
var us_onLoadCalled = false;

function us_onLoad() {
	us_onLoadImpl();
	us_onLoadCalled = true;
	if (us_onLoadOld) {
		us_onLoadOld();
	}
}

us_onLoadOld = window.onload;
window.onload = us_onLoad;

function us_autodetectCharset() {
	var d = document;
	var f = d.getElementById('us_form');
	var ee = f.getElementsByTagName('input');
	for (var i = 0;  i < ee.length;  i++) {
		var e = ee[i];
		if (e.getAttribute('name') == 'charset') {
			if (e.value == '') {
				// http://stackoverflow.com/questions/318831
				e.value = d.characterSet ? d.characterSet : d.charset;
			}
			return;
		}
	}
}

function us_onSubmit() {
	
	if (!us_onLoadCalled) {
		alert('us_onLoad() has not been called')
		return false;
	}

	function trim(s) {
		return s == null ? '' : s.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
	}

	var d = document;
	var f = d.getElementById('us_form');
	if (!f) {
		alert('Internal error: form not found.');
		return false;
	}
	
	var ee, i, e, n, v, r, k, b1, b2;
	var hasEmail = false;
	var hasPhone = false;

	ee = f.getElementsByTagName('input');
	for (i = 0;  i < ee.length;  i++) {
		e = ee[i];
		n = e.getAttribute('name');
		if (!n || e.getAttribute('type') != 'text') {
			continue;
		}

		v = trim(e.value);
		if (v == '') {
			k = e.getAttribute('_required');
			if (k == '1') {
				alert(us_msg['missing'].replace('%s', e.getAttribute('_label')));
				e.focus();
				return false;
			}
			continue;
		}

		if (n == 'email') {
			hasEmail = true;
		} else if (n == 'phone') {
			hasPhone = true;
		}
		
		k = e.getAttribute('_validator');
		r = null;
		switch (k) {
			case null:
			case '':
				break;
			case 'email':
				// TODO Provide regexps from PHP code (add getEmailValidationRegexp_forJavascript() to functions.php).
				r = /^[a-zA-Z0-9_+=-]+[a-zA-Z0-9\._+=-]*@[a-zA-Z0-9][a-zA-Z0-9-]*(\.[a-zA-Z0-9]([a-zA-Z0-9-]+))*\.([a-zA-Z]{2,6})$/;
				break;
			case 'phone':
				r = /^[\d +()\-]{7,32}$/;
				break;
			case 'float':
				r = /^[+\-]?\d+(\.\d+)?$/;
				break;
			default:
				alert('Internal error: unknown validator "' + k + '"');
				e.focus();
				return false;
		}
		if (r && !r.test(v)) {
			alert(us_msg['invalid'].replace('%s', e.getAttribute('_label')));
			e.focus();
			return false;
		}
	}

	if (!hasEmail && !hasPhone) {
		alert(us_msg['email_or_phone']);
		return false;
	}

	ee = f.getElementsByTagName('input');
	b1 = false;
	b2 = false;
	for (i = 0;  i < ee.length;  i++) {
		e = ee[i];
		if (e.getAttribute('name') != 'list_ids[]') {
			continue;
		}
		b1 = true;
		if (e.checked) {
			b2 = true;
			break;
		}
	}
	if (b1 && !b2) {
		alert(us_msg['no_list_ids']);
		return false;
	}

	return true;
}
