/**
 * rescripts
 */
jQuery(document).ready(function(){
    jQuery('html').eq(0).addClass('js_on')
    jQuery.extend(jQuery.validator.messages, { 
      required: "…обязательное поле…",
      email:'…e-mail не соответствует формату…',
      equalTo:'…пароли не совпадают…'
    });
    //jQuery('#image_ban, #flash_ban').tablesorter();
    jQuery('.sw-tabs').tabs({
        selected: 0,
        fx: {
            opacity: 'toggle'
        }
    });
	$('#banners').tabs({
        selected: 0,
        fx: {
            opacity: 'toggle'
        },
		show: function(event, ui){
			//alert(jQuery(this).tabs('option', 'selected'));
			var selected = jQuery(this).tabs('option', 'selected');
			switch(selected) {
				case 0:
				    var taba = jQuery('#flash_ban');
					break;
				case 1:
				    var taba = jQuery('#image_ban');
					break;
			}
			insertBanner(jQuery('a',taba).eq(0));
		}
    });
	jQuery('#image_ban_box .jslink, #flash_ban_box .jslink').each(function(){
		jQuery(this).click(function(e){
			e.preventDefault();
			insertBanner(jQuery(this));
		})
	})
	function insertBanner(el, context){
		var parent = jQuery(el).parent('li');
        var next = jQuery(el).next('div');
		var href = jQuery(el,context).attr('href');
		if(next.length == 0) {
				parent.addClass('loading');
                var flashAjaxBox = jQuery('<div class="ajax-loaded"></div>').appendTo(parent);
                flashAjaxBox.load(href + ' .sw-banner-code, .sw-banners-eg',
                           function(){
                              parent.removeClass('loading');
                              jQuery('.ajax-loaded',parent.siblings()).slideUp(400);
                              var flashvars = {
                                    bannerLink: jQuery('.flash-ajax-box', flashAjaxBox).attr('bannerLink'),
                                    url: jQuery('.flash-ajax-box', flashAjaxBox).attr('url')
                                }
                                swfobject.embedSWF(jQuery('.flash-ajax-box', flashAjaxBox).attr('img')+'.swf', jQuery('.flash-ajax-box', flashAjaxBox).attr('id'), jQuery('.flash-ajax-box', flashAjaxBox).attr('w'), jQuery('.flash-ajax-box', flashAjaxBox).attr('h'), jQuery('.flash-ajax-box', flashAjaxBox).attr('version'), '', flashvars);
                           });
            } else {
				jQuery('.ajax-loaded',parent.siblings()).slideUp(400);
                next.slideDown(400);
            }
	}
    var usableForm = jQuery('.usable_form');
    var rounded = '<span class="k-round"><b></b><i></i></span>';
    usableForm.each(function(){
        jQuery(this).wrap('<div class="obertkaform k-bordered"></div>');
        jQuery(rounded).insertBefore(jQuery(this)).addClass('k-round-t');
        jQuery(rounded).insertAfter(jQuery(this)).addClass('k-round-b');
    })
    jQuery('textarea','.sw-banner-code').focus(function(){
        jQuery(this).select();
    })
    jQuery('.selector').show().click(function(e){
        e.preventDefault();
        jQuery(jQuery(this).attr('href')).select();
    })
    //jQuery('.sw-tabs').tabs();
    var icoSaveClients = jQuery('.ico-save','#list');
    icoSaveClients.each(function(){
        var clientHash = jQuery('#hash_'+jQuery(this).attr('id'));
        var clientName = jQuery('#client_'+jQuery(this).attr('id'));
        jQuery(this).bind('click',function(){
           clientName.addClass('loading');
           saveClient(clientHash,clientName);
        })
        clientName.bind('keypress',function(e){
            if (e.keyCode == 13) {
                clientName.addClass('loading');
                saveClient(clientHash,clientName);
                jQuery(this).blur();
            }
        })
    })
    var statClient = jQuery('#stat_client');
    var statClientOptions = jQuery('option',statClient);
    statClient.bind('change',function(){switchStat();});
    var switchStat = function(){
        statClientOptions.each(function(){
            
            if (jQuery(this).attr('selected') == true){
                jQuery('#c'+jQuery(this).val()).show();
                console.log('#c'+jQuery(this).val());
            } else {
                jQuery('#c'+jQuery(this).val()).hide();
            }
        })
    };
    switchStat();
    // выбираем WM-кошельки
    var wms = jQuery('input[name="wm_wallet"]','#wm_wallets');
    wms.each(function(){
        if(jQuery(this).is(':checked')) {
        	jQuery(this).parents('.wm-checkradio').addClass('wm-checked');
        }
        jQuery(this).click(function(){
        	wms.attr('checked',false).parents('.wm-checkradio').removeClass('wm-checked');
        	jQuery(this).attr('checked',true).parents('.wm-checkradio').addClass('wm-checked')
        })
    });
    jQuery(':text,:password','#login_form').each(function(){
    	jQuery(this).focus(function(){
    		//console.log(jQuery(this).val() + '///' + jQuery(this).attr('defaultValue'));
    		if(jQuery(this).val() == jQuery(this).attr('defaultValue') ) {
    			jQuery(this).val('');
    		}
    	})
    	jQuery(this).blur(function(){
    		//console.log(jQuery(this).val() + '///' + jQuery(this).attr('defaultValue'));
    		if(jQuery(this).val() == '' || !jQuery(this).val()) {
    			jQuery(this).val(jQuery(this).attr('defaultValue'));
    		}
    	})
    })
    /*
jQuery('.btn').each(function(){
    	if(jQuery(this).hasClass('btn-s')){
    		jQuery(this).removeClass('btn-s').removeClass('btn');
    		jQuery(this).wrap('<span class="btn btn-s"><span><span><span></span></span></span></span>');
    	}
    })
*/
    btnWrap();
    jQuery(':text,:password,textarea').each(function(){
    	jQuery(this).focus(function(){
    		jQuery(this).addClass('focused');
    	});
    	jQuery(this).blur(function(){
    		jQuery(this).removeClass('focused');
    	})
    })
    jQuery('th','#mainnav').hover(function(){
    	jQuery(this).addClass('thover');
    },function(){
    	jQuery(this).removeClass('thover');
    });
    jQuery('#login_form').validate({
        rules:{
            login:'required',
            password:'required'
        }
    });
    jQuery.datepicker.setDefaults($.datepicker.regional['ru']);
    jQuery('#date_from, #date_to').datepicker({
    	changeMonth: true,
    	changeYear: true,
    	dateFormat: 'yy-mm-dd',
    	clickInput: true,
    	showOtherMonths: true,
    	nextText:'→',
    	prevText:'←'
    });
    //jQuery('').datepicker();
})
function saveClient(hash,name) {
    $.post(
        '/update/clients/'+ hash.val(),
        {descr: name.val()},
        function(data){
            window.setTimeout(function(){name.removeClass('loading');}, 500);
        }, 'json'
    );
}
function btnWrap(){
	jQuery('.btn').each(function(){
        if(jQuery(this).hasClass('btn-s')){
            jQuery(this).removeClass('btn-s').removeClass('btn');
            jQuery(this).wrap('<span class="btn btn-s"><span><span><span></span></span></span></span>');
        }
    })
}
