﻿// фиксит баги в каталоге для IE
function fixCatalogTooltip() {
    if ($("ul.catalog").size() > 0) {
        $("ul.catalog li").hover(function(){
            $(this).css("z-index", "2");
        },function(){
            $(this).css("z-index", "1");
        });
        $("ul.catalog div.pic").hover(function(){
            $(this).addClass("jshover");
        },function(){
            $(this).removeClass("jshover");
        });
    }
}

function initSccrollH (current) {
    var total = 0;
    $(current).find("li").each(function(i){total += 159;});
    $(current).find("ul").width(total);
    $(current).jScrollHorizontalPane({showArrows:true, scrollbarHeight: 11, arrowSize: 11});
}

function reloadPage() {
    $("body").css("display","inline").css("display","block");
}

function initAll() {
     	
    if ($.browser.msie) {fixCatalogTooltip();};
    $(".scroll").each(function() {$(".scroll").jScrollPane({showArrows:true, scrollbarWidth: 11});});

    $(".scrollh").each(function() {if ($(".scrollh").parent('.section').css("display")=="block") {initSccrollH(this);}});

    $("p.section-title").each(function() {
        $(this).unbind("click");
        $(this).click(function(){
            $(this).toggleClass("expanded");
            if ($.browser.msie) {$(this).next(".section").toggle();}
            else {$(this).next(".section").slideToggle(250,function(){reloadPage();});}
            if ($(this).next(".section").not(".hidden")) {initSccrollH($(this).next(".section").find(".scrollh"));}
            reloadPage();
        });
    });

	if( typeof _____jquery_ui_datepicker_____ == 'function' )
	{
		$("input.selectdate").each(function() { 
			var inputobj = $(this);
			if( inputobj.attr( "name" ).indexOf("birth") == -1 )
			{
				inputobj.datepicker( { dateFormat: 'dd.mm.yy' } );
			}
			else
			{
				inputobj.datepicker( { dateFormat: 'dd.mm.yy', yearRange: '1930:1991' } );
			}
			inputobj.attr("readonly", "true" );
			var inputname = inputobj.attr("name")
			var imgobj = $("#img_" + inputname );
			if( imgobj.length )
			{
				imgobj.click(function() {
					$(inputobj).datepicker( "show" ); 
					return false;
				})				
			}
		});
	}
    addReadOnlyClass();
    reloadPage();
}

function loadNews()
{
	$(".news").each( function(i)
	{
		if( i>1 )
		{
			alert("Поддерживается только один блок новостей!");
			return;
		}
		category = this.id.replace("news_", "" );
		u = '/serv/news.php'
		if( category != '' )
		{
			u = u + "?category="+category;
		}
		news_block=this;
		$(news_block).html( '<img src="images/ajax-loader2.gif"/>' );
	    jQuery.getFeed({
    	    url: u,
        	success: function(feed) {
            	var html = "";
            	if( feed.items.length > 0 )
            	{
		            html += '<ul class="news">';
    		        for(var i = 0; i < feed.items.length && i < 3; i++) {   
        		        var x = new Date(feed.items[i].updated);
            		    html += '<li><var>';
                		html += x.getDate() + '.' + x.getMonth() + '.' + x.getFullYear();
	                	html += '</var><p><a href="';
	    	            html += feed.items[i].link;
    	    	        html += '" target="_blank">';
        	    	    html += feed.items[i].title;
            	    	html += '</a></p></li>';
	            	}
	    	        html += '</ul>';
				}
				else
				{
					html = "Новости отсутствуют";
				}
        	    $(news_block).html( html );
	        }    
    	});
	});
}

$(document).ready(function(){

    if(typeof registrationBoxInit == 'function') { registrationBoxInit(); };

    if(typeof customerPerformerProfileInit == 'function') { customerPerformerProfileInit(); }
    if(typeof customerJoinInit == 'function') { customerJoinInit(); }
    if(typeof customerProfileInit == 'function') { customerProfileInit(); }
    if(typeof customerChatInit == 'function') { customerChatInit(); }
    if(typeof customerPayInit == 'function') { customerPayInit(); }
    if(typeof performerGalleryInit == 'function') { performerGalleryInit(); };
    if(typeof performerJoinInit == 'function') { performerJoinInit(); }
    if(typeof performerProfileInit == 'function') { performerProfileInit(); }

    if(typeof managerProfileInit == 'function') { managerProfileInit(); }


    if(typeof managerJoinInit == 'function') { managerJoinInit(); }

    //loadNews();

    initAll();
    
    initCheck();

})


  function S4()
  {
    return (((1+Math.random())*0x10000)|0).toString(10).substring(1);
  }
  
  function GUID()
  {  
    return (S4()+S4()).toUpperCase();
  }

function addReadOnlyClass(){
     $("input").each(function (i) {
	  if ($(this).attr("readonly")){
		$(this).removeClass("text").addClass("readonly").addClass("textR");
	    }			   
	}
    );
}

function onSuccessSubmit(param,status){
	document.location.href='/exec/performer/gallery/public';
		
}

function onSuccessSubmitPer(param,status){
	document.location.href='/exec/performer/profile/3';
		
}

function submitBlockForm(flag){	
	var options_submit={
		success:onSuccessSubmit
	}

	var options_submit_per={
		success:onSuccessSubmitPer
	}
	
	var select = document.getElementsByName('performer_custom_payment_type')[0];
	if (select && !flag)
	{
		var inputN = 'performer_custom_'+select.value;
		var input = document.getElementsByName(inputN)[0]; 
		if (input.value == '')
		{
			if( !confirm('ВНИМАНИЕ! Не указан номер кошелька. Рекомендуем в ближайшее время указать его, иначе мы не сможем осуществлять выплаты.  Продолжить?'))
			{
				return false;
			}
		}
	
		var scan = document.getElementsByName('performer_custom_2257_1')[0]; 
		var passport= document.getElementsByName('performer_custom_2257_2')[0]; 
		if ( (scan && scan.value=='') || (passport && passport.value==''))
		{
//			if( !confirm('ВНИМАНИЕ! Не указан скан и/или фото с паспортом. Для утверждения анкеты нам необходимо убедиться в совершеннолетии модели. Отправить скан и фото позже можно по электронной почте vprivate.ru@gmail.com. До этого момента доступ в эккаунт будет заблокирован. Продолжить?') )
			alert( 'ВНИМАНИЕ! Не указан скан и/или фото с паспортом. Для утверждения анкеты нам необходимо убедиться в совершеннолетии модели. Отправить скан и фото позже можно по электронной почте vprivate.ru@gmail.com. После этого Вы сможете завершить регистрацию и приступить к работе' );
			{
				return false;
			}
		}
		$("#frm_performer_pforile").ajaxSubmit(options_submit_per);
	}
	else
	{
		$("#frm_performer_pforile").ajaxSubmit(options_submit);
	}
}




function onSuccessSubmitSMS(param,status){
	res = param.split("/r/n");	
	mes = res[0].trim();	
	$('#smsText').attr('value','');
	$("#smsTextTrans").attr('value','');
	$('#kolSymb').attr('value','140');
	if (res[1]){
        	$("#headerbalance").html(res[1].trim());
	}
	alert(mes);			
	//location.href='';
}


function submitSMSForm(){
	
	var options_submit={
		success:onSuccessSubmitSMS
	}

	if (!$("#sms").attr("checked") && !$("#email").attr("checked") && !$("#pers").attr("checked")){
		alert ("Выберите тип сообщения!");
	}else
	if ($("#smsText").attr("value").length == 0){
		alert ("Введите сообщение");
		$("#smsText").focus();
	}else{
	        $("#smsTextTrans").attr("value",""); 	 
		$("#customer_screen").attr("value",translateStr($("#customer_screen").attr("value")));					
		$("#smsTextTrans").attr("value",translateStr($("#smsText").attr("value"))); 
		$("#smsform").ajaxSubmit(options_submit); 
	}
}


String.prototype.trim = function() { var temp= this.replace(/^\s+|\s+$/, '');return temp.replace(/^\n+|\n+$/, '');};


function initCheck(){
    var option_login_customer = {callback: checkLoginCustomer,captureLength: 0,wait : 750};
    var option_login_perfomer = {callback: checkLoginPerfomer,captureLength: 0,wait : 750};
    var option_login_manager = {callback: checkLoginManager,captureLength: 0,wait : 750};

    var option_screen_customer = {callback: checkScreenCustomer,captureLength: 0,wait : 750};
    var option_screen_perfomer = {callback: checkScreenPerfomer,captureLength: 0,wait : 750};

    $("input").each(function (i) {
	if ($(this).attr('name') == 'customer_name'){
		if ($(this).parents('form:eq(0)').attr('id') == 'performerloginform' || $(this).parents('form:eq(0)').attr('action') == '/exec/login'){
		
		}else{

		$(this).typeWatch(option_login_customer);
		$(this).blur(function(){		
			if (this.value.length == 0){
			   $("#errorLabelL").show();
			   $("#errorLabelL").html("This field is required.");
			}
		});}
	}

	if ($(this).attr('name') == 'performer_name'){
		if ($(this).parents('form:eq(0)').attr('id') == 'performerloginform'){
		
		}else{

		$(this).typeWatch(option_login_perfomer);
		$(this).blur(function(){		
			if (this.value.length == 0){
			   $("#errorLabel").show();
			   $("#errorLabel").html("This field is required.");
			}
		});}
	}
	
	if ($(this).attr('name') == 'manager_name'){
		if ($(this).parents('form:eq(0)').attr('id') == 'performerloginform'){
		
		}else{
		
		$(this).typeWatch(option_login_manager);		
		$(this).blur(function(){		
			if (this.value.length == 0){
			   $("#errorLabel").show();
			   $("#errorLabel").html("This field is required.");
			}
		});}

	}

	if ($(this).attr('name') == 'customer_screen_name'){
		$(this).typeWatch(option_screen_customer);
		$(this).blur(function(){		
			if (this.value.length == 0){
			   $("#errorLabelSL").show();
			   $("#errorLabelSL").html("This field is required.");
			}
		});

	}

	if ($(this).attr('name') == 'performer_screen_name'){
		$(this).typeWatch(option_screen_perfomer);
		$(this).blur(function(){		
			if (this.value.length == 0){
			   $("#errorLabel").show();
			   $("#errorLabel").html("This field is required.");
			}
		});
	}



    });	

}


function checkLoginCustomer(_login){		
	$("#errorPicL").html( '<img src="images/ajax-loader2.gif" id="imgError"/>' );		
	$.post('/exec/includes/checkLogin.jsp',{login:_login,type:'customers',isExclusive:true},function(data){
		$("#errorPicL").html( '' );		
		var result = data.trim();
		if (result!=''){					
			$("#errorLabelL").show();
			$("#errorLabelL").html(result);
		}else{
			$("#errorLabelL").html('');
			$("#errorLabelL").attr("style","display:none");

		}
		
	});

}

function checkLoginPerfomer(_login){		
	$("#errorPic").html( '<img src="images/ajax-loader2.gif" id="imgError"/>' );		
	$.post('/exec/includes/checkLogin.jsp',{login:_login,type:'performers',isExclusive:true},function(data){
		$("#errorPic").html( '' );		
		var result = data.trim();
		if (result!=''){					
			$("#errorLabel").show();
			$("#errorLabel").html(result);
		}else{
			$("#errorLabel").html('');
			$("#errorLabel").attr("style","display:none");

		}
		
	});

}

function checkLoginManager(_login){		
	$("#errorPic").html( '<img src="images/ajax-loader2.gif" id="imgError"/>' );		
	$.post('/exec/includes/checkLogin.jsp',{login:_login,type:'managers',isExclusive:true},function(data){
		$("#errorPic").html( '' );		
		var result = data.trim();
		if (result!=''){					
			$("#errorLabel").show();
			$("#errorLabel").html(result);
		}else{
			$("#errorLabel").html('');
			$("#errorLabel").attr("style","display:none");

		}
		
	});

}

function checkScreenCustomer(_screen){		
	$("#errorPicSL").html( '<img src="images/ajax-loader2.gif" id="imgError"/>' );		
	$.post('/exec/includes/checkLogin.jsp',{screen:_screen,type:'customers',isExclusive:true},function(data){
		$("#errorPicSL").html( '' );		
		var result = data.trim();
		if (result!=''){					
			$("#errorLabelSL").show();
			$("#errorLabelSL").html(result);
		}else{
			$("#errorLabelSL").html('');
			$("#errorLabelSL").attr("style","display:none");

		}
		
	});

}

function checkScreenPerfomer(_screen){		
	$("#errorPicS").html( '<img src="images/ajax-loader2.gif" id="imgError"/>' );		
	$.post('/exec/includes/checkLogin.jsp',{screen:_screen,type:'performers',isExclusive:true},function(data){
		$("#errorPicS").html( '' );		
		var result = data.trim();
		if (result!=''){					
			$("#errorLabelS").show();
			$("#errorLabelS").html(result);
		}else{
			$("#errorLabelS").html('');
			$("#errorLabelS").attr("style","display:none");

		}
		
	});

}


function checkSMSCount(val){
	var A = $('#smsText').attr('value');
	var B = $('#smsTextTrans').attr('value');
	if ($('#smsTextTrans').attr('value').length>=140 || $('#smsText').attr('value').length>=140){		
		alert('Размер сообщения не должен привышать 140 символов')
		$('#kolSymb').attr('value',0);			
		A = A.substring(0, 139);
		$('#smsText').attr('value',A);
		B = B.substring(0, 139);
		$("#smsTextTrans").attr("value",B); 	 
	}		
	else{	    
	     $("#smsTextTrans").attr("value",""); 	 
	     $("#smsTextTrans").attr("value",translateStr(val)); 	 
	     count = $('#smsTextTrans').attr('value').length;	     	
	     $('#kolSymb').attr('value',140-count);	
	}
}

var mapEn = "A|B|V|G|D|E|E|Zh|Z|I|J|K|L|M|N|O|P|R|S|T|U|F|H|TS|Ch|Sh|Sch|'|Y|'|E|Yu|Ya|e|yu|ya|sch|ch|sh|kh|e|zh|a|b|v|g|d|e|z|i|y|k|l|m|n|o|p|r|s|t|u|f|ts||y|'|".split('|');
var mapRu = "А|Б|В|Г|Д|Е|Ё|Ж|З|И|Й|К|Л|М|Н|О|П|Р|С|Т|У|Ф|Х|Ц|Ч|Ш|Щ|Ъ|Ы|Ь|Э|Ю|Я|э|ю|я|щ|ч|ш|х|е|ж|а|б|в|г|д|е|з|и|й|к|л|м|н|о|п|р|с|т|у|ф|ц|ъ|ы|ь".split('|');


function translateSymbol(str){
         var s = str;
         for(i = 0; i < mapRu.length; i++)
            if (s==mapRu[i])
                return mapEn[i];
         return s
    }

function translateStr(str){
        var rez="";
        for (j = 0; j < str.length; j++){
            rez=rez+translateSymbol(str[j]);
        }
        return rez;
    }


function checkIfEmpty(){
		
}

