
// Blog functions
function showBlogArhive()
{
    var arhive = $("#blog_arhive").val();
    if (arhive == '0') return false;
    
   var year = arhive.substring(0, 4);
   var month = arhive.substring(5, 7);
   
   document.location.href = "/blog/"+year+"/"+month+"/";
    return true;
}

function postComment()
{
    var error = '';
    if (!trim($("#comment_name").val())) error += _LANG['enter_your_name']+'\n';
    if (!trim($("#comment_post").val())) error += _LANG['enter_comment']+'\n';
    if (error) { jAlert(error);return false;}

    var lang_path = $('#lang_path').val();

   $.ajax({
      type: "POST",
      dataType: "html",
      error: function(response){},
      url: lang_path + "blog/comment/add/",
      data: $("#post_comment").serialize(),
      beforeSend: function()
      {
         blockStandart('comments_div');
      },
      complete: function()
      {
         $('#comments_div').unblock();
      },
      success: function(response)
      {
            $("#comments_div").html(response);
      }
   });
   
    return true;
}

function reloadFirstStep()
{
   var step = 1;
   if (!$('#save_first_step').length) step = 2;

   $.ajax({
      type: "POST",
      dataType: "html",
      url: $('#lang_path').val()+"checkout/",
      data: "action=update&storage=0&ajax_step1=1&step="+step+"&" + $('#save_first_step').serialize(),
      beforeSend: function()
      {
         blockStandart('listing');
      },
      complete: function()
      {
         $('#listing').unblock();
      },
      success: function(response)
      {
         $("#listing").html(response);
      }
   });
}

function recalculate()
{
   var step = 1;
   if (!$('#save_first_step').length) step = 2;

   $.ajax({
      type: "POST",
      dataType: "html",
      url: $('#lang_path').val()+"checkout/recalculate/",
      data: "action=update&storage=0&ajax=1&step="+step+"&" + $('#save_first_step').serialize(),
      beforeSend: function()
      {
         blockStandart('first_step_block');
      },
      complete: function()
      {
         $('#first_step_block').unblock();
      },
      success: function(response)
      {
         $("#products_table").html(response);
      }
   });
}

function getShippingPrice(country_id)
{
   var lang_path = $('#lang_path').val();

   $.ajax({
      type: "POST",
      dataType: "html",
      url: lang_path+"checkout/second/",
      data: "ajax=1&shipping_country_id=" + country_id,
      beforeSend: function()
      {
         blockStandart('products_table');
      },
      complete: function()
      {
         $('#products_table').unblock();
      },
      success: function(response)
      {
         $("#products_table").html(response);
      }
   });
}

//
function addToCart(id, quantity, storage)
{
   if (!checkIsIntNumberCorrect(quantity) || quantity <=0 ) { jAlert(_LANG['incorrect_product_quantity']);return false; }
   if (null == storage || undefined == storage) storage = 0;

   addToCartActive(id, quantity, storage);

   return true;
}

function addToCartActive(id, quantity, storage, callback)
{
    var data = "action=add&id="+id+"&quantity="+quantity+"&storage="+storage;
    
    //shipto popup show
    if ($('#cartProductsShiptoCountrySelected').val() == 0)
    {
        showPopup(300, $('#lang_path').val()+'shipto_popup/', data);
        return false;
    }    
     
   $.ajax({
      type: "POST",
      url: $('#lang_path').val()+"cart/add/",
      data: data,
      dataType: "html",
      beforeSend: function()
      {
         blockStandart('cart_block_1');
      },
      complete: function(){  },
      success: function(response){
            if (response == '_first_item') { //no need in this action, look higher (shipto popup show)
                $('#cart_block_1').unblock();
                showPopup(300, $('#lang_path').val()+'shipto_popup/', data);
            } else if (response == '_cant_add') {
                $('#cart_block_1').unblock();
                if (jConfirm(_LANG['cant_ship_product_to_selected_country'], 'Warning', function(v){
                    if (v) {
                        if (callback) { callback();return true; }
                        else return false;
                    }
                }));
                
            }
            else if (!response) {
                if (callback) { callback();return true; }
                else cartReload();
            }
            else {  $('#cart_block_1').unblock(); jAlert(response); }
      }
   });
}

function removeFromCart(id)
{
    var lang_path = $('#lang_path').val();

   if (confirm_delete())
   {
      $.ajax({
         type: "POST",
         url: lang_path+"cart/remove/",
               data: "action=del&id="+id,
         dataType: "html",
         complete: function(){},
         beforeSend: function(){
            if ($('#cart_block_1').length)
            {
                $('#cart_row_'+id).remove();
                $('#shoppingCartSpan').html(parseInt($('#shoppingCartSpan').text())-1);
            } else if ($('#products_table').length) {
                $('#product_'+id).remove();
            }
         },
         success: function(data){
            if ($('#cart_block_1').length)
            {
                 cartReload();
            } else if ($('#products_table').length) {
                if (data == 0) window.location.reload();
                else reloadFirstStep();
            }
         }
      });
   }
}

function cartReload(action)
{
        $.ajax({
            type: "POST",
            url: $('#lang_path').val(),
            data: 'call=component&name=cart&action='+action+'&' + $('#cartForm').serialize(),
            dataType: "html",
             beforeSend: function()
             {
                if ($('#cart_block_1 .blockUI').size() == 0 )
                {
                    blockStandart('cart_block_1');
                }
             },
             complete: function()
             {
                 $('#cart_block_1').unblock();
             },
            success: function(response){
                $('#cart_block_1').html(response);
            }
        });
}

function validateCheckoutForm()
{
   var error = '';
   var wrongField = null;
   if (!trim($("#bill_firstname").val())) {
       if ( null == wrongField ) wrongField = $("#bill_firstname");
       error += _LANG['empty_firstname']+'\n';
   }
   if (!trim($("#bill_lastname").val())) {
       if ( null == wrongField ) wrongField = $("#bill_lastname");
       error += _LANG['empty_lastname']+'\n';
   }
   if (!trim($("#bill_address1").val())) {
       if ( null == wrongField ) wrongField = $("#bill_address1");
       error += _LANG['empty_address']+'\n';
   }
   if (!trim($("#bill_city").val())) {
       if ( null == wrongField ) wrongField = $("#bill_city");
       error += _LANG['empty_city']+'\n';
   }
   if (!trim($("#bill_zip").val())) {
       if ( null == wrongField ) wrongField = $("#bill_zip");
       error += _LANG['empty_postal_code']+'\n';
   }
   if ($("#bill_country").attr("selectedIndex") == 0) {
       if ( null == wrongField ) wrongField = $("#bill_country");
       error += _LANG['empty_country']+'\n';
   }
   if ($("#bill_phone_code").val() <= 0) {
       if ( null == wrongField ) wrongField = $("#bill_phone_code");
       error += _LANG['empty_phone_code']+'\n';
   }
   if (!trim($("#bill_phone").val())) {
       if ( null == wrongField ) wrongField = $("#bill_phone");
       error += _LANG['empty_phone'] + '\n';
   }

   if ($("#bill_mobile_code").val() <= 0 && trim($("#bill_mobile").val())) {
       if ( null == wrongField ) wrongField = $("#bill_mobile_code");
       error += _LANG['empty_mobile_code']+'\n';
   }
   if ($("#bill_fax_code").val() <= 0 && trim($("#bill_fax").val())) {
       if ( null == wrongField ) wrongField = $("#bill_fax_code");
       error += _LANG['empty_fax_code']+'\n';
   }

   if (!trim($("#bill_email").val()))
   {
        if ( null == wrongField ) wrongField = $("#bill_email");
        error += _LANG['empty_email']+'\n';
   }else{
        if (!checkEmail($("#bill_email").val())) {
            if ( null == wrongField ) wrongField = $("#bill_email");
            error += _LANG['incorrect_email']+'\n';
        }
   }

   if ($("#ship_to_mobile_code_id").val() <= 0 && trim($("#ship_to_mobile").val())) error += _LANG['empty_ship_mobile_code']+'\n';

   if ($("#ship_to_country_id").attr("selectedIndex") == 0) error += _LANG['empty_ship_to_country']+'\n';

   if (error) {
       jAlert(
        	error,
        	"",
        	function() {
                if ( wrongField != null ) {
                    wrongField.focus();
                }
        	});
       return false;
   }

return true;
}

function checkout()
{
    var lang_path = $('#lang_path').val();

    //save data to session
      $.ajax({
         type: "POST",
         url: lang_path+"checkout/save_session/",
         data:  $('#billing_info_form').serialize(),
         dataType: "html"
      });

    if (validateCheckoutForm())
    {
        var error = false;
        var warning = false;
        var shipto_country_old = 0;
        var url = $('#lang_path').val()+"checkout/save/?ajax_second=1&checkout=1&shipto_id="+$('#ship_to_country_id').val();
        blockStandart('listing');
        $.getJSON(url,
            function(data){
              //$('#listing').unblock();
                  $.each(data, function(key, value) {
                        if ("error_html" == key)
                        {
                            error = true;
                        } else if ("error_gold_limit_for_uk" == key) {
                            error = true; 
                        } else if ("warning_country_markup" == key) {
                            warning = value;
                        } else if ("shipto_country_old" == key) {
                            shipto_country_old = value;
                        }
                  });
                  
            if (error) { document.location.href= lang_path+'checkout/'; return false; }
            else if (warning) { 
                if (jConfirm(warning, 'Warning', function(v){
                    if (v) {
                        sub_checkout();
                    } else {
                        $('#ship_to_country_id').val(shipto_country_old);
                        var url = $('#lang_path').val()+"shipto_popup/" + "?shipto_id="+shipto_country_old;
                        $.getJSON(url,
                            function(data){ }
                        );
                        $('#listing').unblock();
                        return false;
                    }
                })); 
            } else {
                sub_checkout();
            }
       }); 
               
    }

    return false;
}

function sub_checkout()
{
    var lang_path = $('#lang_path').val();
      $.ajax({
         type: "POST",
         url: lang_path+"checkout/save/",
         data:  $('#billing_info_form').serialize(),
         dataType: "html",
         beforeSend: function()
         {
            blockStandart('listing');
         },
         success: function(response){
            //$('#listing').unblock();
            document.location.href=lang_path+'checkout/complete/';
         }
      });    
}

//   function openWindowCvv2(internalURL, thisW, thisH)
//   {
//      internalArgs = 'scrollbars,resizable,toolbar,status,left=50,top=50,width=' + thisW + ',height=' + thisH;
//      popupWin = window.open(internalURL, 'mlPopupWinCvv2', internalArgs);
//      popupWin.focus();
//   }

   function showHiddenInput(type)
   {
      if ( document.getElementById(type + 'RecordName') == null) return;

      if ( document.getElementById(type + 'RecordName').value != '' )
      {
         document.getElementById('add_to_' + type + 'to_address_book_span').style.visibility = "visible";
         document.getElementById('add_to_' + type + 'to_address_book').disabled = false;
      }
      else
      {
         document.getElementById('add_to_' + type + 'to_address_book_span').style.visibility = "hidden";
         document.getElementById('add_to_' + type + 'to_address_book').disabled = true;
      }
   }

//FRONTEND
function validateRegisterForm()
{
    var error = '';
    var wrongField = null;
    if ( $("#user_username").length )
    {
    	var username = trim($("#user_username").val());
        if ( !username )
        {
            error += _LANG['empty_username']+'\n';
            wrongField = $("#user_username");
        }
        else if ( username.length < 4 )
        {
            error += _LANG['username_length']+'\n';
            wrongField = $("#user_username");
        }
    }

    if ( !$("#pass1").val() )
    {
        error += _LANG['empty_password']+'\n';
        if ( null == wrongField ) wrongField = $("#pass1");
    }
    else if ( $("#pass1").val() != $("#pass2").val() || $("#pass1").val() == '' )
    {
        error += _LANG['passwords_not_match']+'\n';
        if ( null == wrongField ) wrongField = $("#pass2");
    }
    if ($('#account_type').val()==2 && !$("#user_company_name").val())
    {
        error += _LANG['empty_company']+'\n';
        if ( null == wrongField ) wrongField = $("#user_company_name");
    }
    if (!$("#user_firstname").val())
    {
        error += _LANG['empty_firstname']+'\n';
        if ( null == wrongField ) wrongField = $("#user_firstname");
    }
    if (!$("#user_lastname").val())
    {
        error += _LANG['empty_lastname']+'\n';
        if ( null == wrongField ) wrongField = $("#user_lastname");
    }
    if ( $("#user_gender").val() <= 0 )
    {
        error += _LANG['select_gender']+'\n';
        if ( null == wrongField ) wrongField = $("#user_gender");
    }
    if (!$("#user_address").val())
    {
        error += _LANG['empty_address']+'\n';
        if ( null == wrongField ) wrongField = $("#user_address");
    }
    if (!$("#user_city").val())
    {
        error += _LANG['empty_city']+'\n';
        if ( null == wrongField ) wrongField = $("#user_city");
    }
    if (!$("#user_zip").val())
    {
        error += _LANG['empty_postal_code']+'\n';
        if ( null == wrongField ) wrongField = $("#user_zip");
    }
    if ($("#bill_to_country_id").val() <= 0)
    {
        error += _LANG['empty_country']+'\n';
        if ( null == wrongField ) wrongField = $("#bill_to_country_id");
    }
    if (!isValidDate($("#dob").val()) && $('#dob_field').css('display') != 'none') //UK
    {
        error += _LANG['incorrect_dob']+'\n';
        if ( null == wrongField ) wrongField = $("#dob");
    }
    if ($("#phone_code").val() <= 0)
    {
        error += _LANG['empty_phone_code']+'\n';
        if ( null == wrongField ) wrongField = $("#phone_code");
    }
    if (!$("#user_phone").val())
    {
        error += _LANG['empty_phone']+'\n';
        if ( null == wrongField ) wrongField = $("#user_phone");
    }
    if ($("#user_fax").val() && $("#fax_code").val() <= 0)
    {
        error += _LANG['empty_fax_code']+'\n';
        if ( null == wrongField ) wrongField = $("#fax_code");
    }
    if ($("#user_mobile").val() && $("#mobile_code").val() <= 0)
    {
        error += _LANG['empty_mobile_code']+'\n';
        if ( null == wrongField ) wrongField = $("#mobile_code");
    }
    if ( !$("#email").val() )
    {
        error += _LANG['empty_email']+'\n';
        if ( null == wrongField ) wrongField = $("#email");
    }
    else if (!checkEmail($("#email").val()))
    {
        error += _LANG['incorrect_email']+'\n';
        if ( null == wrongField ) wrongField = $("#email");
    }

    //if ($("#user_username").size() && !$("#code_word").val()) error += 'Fill "Security Word" field\n';
    //if (!isValidDate($("#dob").val())) error += 'Incorrect "Date of birth"\n';
    if ( $('#how_know_type').length )
    {
        if ( $('#how_know_type').val() <= 0 )
        {
            error += _LANG['select_where_did_you_here']+'\n';
            if ( null == wrongField ) wrongField = $("#how_know_type");
        }
        if ( $('#how_know_type').val() != 7 && !$('#how_know_text').val() )
        {
            error += _LANG['empty_where_did_you_here']+'\n';
            if ( null == wrongField ) wrongField = $("#how_know_text");
        }
    }
    if ( $('#captcha').length && !$('#captcha').val() )
    {
        error += _LANG['empty_code']+'\n';
        if ( null == wrongField ) wrongField = $("#captcha");
    }

    if ( error.length > 0 )
    {
        jAlert(
        	error,
        	"",
        	function()
        	{
                if ( wrongField != null )
                {
                    wrongField.focus();
                }
        	});
        return false;
    }

    return true;
}

function registerUser()
{
    var lang_path = $('#lang_path').val();

    if (validateRegisterForm())
    {
        $.ajax({
           type: "POST",
           dataType: "html",
           url: $('#url').val(),
           data: 'how_know_which_text='+ $('#how_know_type :selected').text() + '&' + $('#register_form').serialize(),
             beforeSend: function()
             {
                blockStandart('listing');
             },
             complete: function()
             {
                $('#listing').unblock();
             },
           success: function(response)
           {
                if (response) { jAlert(response); } //login error
                else { window.location.href = lang_path+"confirmation_letter_send.html"; } //login successfull //TODO!!!
           }
        });
    }

    return;
}
function saveSubscription()
{
        $.ajax({
           type: "POST",
           dataType: "html",
           url: $('#url').val(),
           data: $('#register_form').serialize(),
           beforeSend: function(){},
           complete: function(){},
           success: function(response)
           {
                if (response) { jAlert(response); } //login error
                else jAlert(_LANG['saved_successfully']);
           }
        });

    return;
}

function addSubscriptionDialog(email)
{
    if (checkEmail(email))
    {
        $.ajax({
           type: "POST",
           dataType: "html",
           url: $('#lang_path').val()+'register.html',
           data: 'action=add_subscription&email='+email,
           beforeSend: function(){},
           complete: function(){},
           success: function(response)
           {
                if (response > 0) {
                    $('#is_subscriber').attr('checked', '');
                    $('#is_subscriber_block').hide();
                }
                else
                {
                    $('#is_subscriber_block').show();
                    $('#is_subscriber').attr('checked', '');
                }
           }
        });
    } else {
        $('#is_subscriber').attr('checked', '');
        $('#is_subscriber_block').hide();
    }

    return false;
}

function closeWarningBox()
{
        $.ajax({
           type: "POST",
           dataType: "html",
           url: $('#lang_path').val(),
           data: 'close_warning_block=1',
           beforeSend: function(){},
           complete: function(){ $("#warning_box_table_tr").remove();}
        });
}

function changeLanguage(lang)
{
    var newdata = window.location.pathname.split("/");
    var curLang = newdata[1];
    if (curLang.length < 3)
    {
        var newpath = '/'+lang;
        $.each(newdata, function(k,v){
            if (k > 1) {
                newpath += '/'+v;
            }
        });
        window.location.href = newpath;
    }
}

function paginator(url, params, div)
{
    $.ajax({
        type: "POST",
        dataType: "html",
        url: url,
        data: params,
        success: function (response)
        {
            $("#"+div).html(response);
        },
        beforeSend: function()
        {
            blockStandart(div);
        },
        complete: function()
        {
            $("#"+div).unblock();
        }
    });
}

function showPopup(nWidth, url, data)
{
    $('#modalContent').html("");
    $('#modalPreloader').css('display', 'block');

    if (nWidth > 0)
    {
        //block screen
        $('#body').block({
            message: $('#modalWindow'),
            centerY: false,
            css:
            {
                top: getBodyScrollTop() + 40,
                left: ($(window).width() - nWidth) /2 + 'px',
                width: nWidth + 'px'
            }
        });
    }

    //get contents
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: "html",
        complete: function(){},
        success: function(response)
        {
            $('#modalPreloader').css('display', 'none');
            $('#modalContent').html(response);
        },
        complete: function()
        {
            $(".blockOverlay").css('height',$(document).height());
        }
    });
}

function showPopupHtml(nWidth, htmlData)
{
    $('#modalContent').html("");
    $('#modalPreloader').css('display', 'block');

    if (nWidth > 0)
    {
        //block screen
        $('#body').block({
            message: $('#modalWindow'),
            centerY: false,
            css:
            {
                top: getBodyScrollTop() + 40,
                left: ($(window).width() - nWidth) /2 + 'px',
                width: nWidth + 'px'
            }
        });
    }

    $('#modalPreloader').css('display', 'none');
    $('#modalContent').html(htmlData);
    $(".blockOverlay").css('height',$(document).height());
}

function closePopup()
{
    $('#modalContent').html("");
    $('#body').unblock();
}

function shiptoCountryChangeSelect(country_id, callbackOption)
{
    if (country_id <= 0) return false;

    //get contents
    $.ajax({
        type: "POST",
        url: $('#lang_path').val()+"shipto_popup/",
        data: 'action=markup_check&shipto_id='+country_id,
        dataType: "html",
        complete: function(){},
        success: function(response)
        {
            if (response && callbackOption != 2)
            {
                var data = response.split('|=|');
                if (jConfirm(data[1], 'Warning', function(v){
                    if (v) {
                        sub_shiptoCountryChangeSelect(country_id, callbackOption);
                    } else {
                        $('#ship_to_country').val(data[0]);
                        $('.shiptoCountrySelectBox').remove();
                        $('#ship_to_country').customStyle('shiptoCountry');                        
                    }
                }));       
            } else {
                sub_shiptoCountryChangeSelect(country_id, callbackOption);
            }   
        },
        complete: function()
        {

        }
    });
}    

function sub_shiptoCountryChangeSelect(country_id, callbackOption)    
{
    var url = $('#lang_path').val()+"shipto_popup/" + "?shipto_id="+country_id;
    var error = '';
    $.getJSON(url,
        function(data){
          if (callbackOption == 1) { window.location.reload(); return false; }


          $.each(data, function(key, value){
                error += value+"\n";
          });
          if (error) {
              //jAlert(_LANG['cant_be_shipped'] + error);
                if (jConfirm(_LANG['cant_be_shipped'] +'\n'+ error, 'Warning', function(v){
                    if (v) {
                        window.location.reload(); return false;
                    }
                }));              
          }
          if (callbackOption == -1 && !error) { window.location.reload(); return false; }
          if (callbackOption == 2 && !error) window.location.href = $('#lang_path').val()+"checkout/";
    });
}


function changePreferredLanguage(theForm)
{
    var usersGender = {"en":{"1":"Mr","2":"Miss\/Mrs"},"de":{"1":"Herr","2":"Frau"}};

    var gendersCount = theForm.user_gender.options.length;
    var selectedLang = theForm.preferred_language.value;
    for ( var i = 1; i < gendersCount; i++ )
    {
        theForm.user_gender.options[i].text = usersGender[selectedLang][i];
        theForm.user_gender.options[i].label = usersGender[selectedLang][i];
    }
}
$(function(){
   var in_1 = 1;
   var in_2 = 0;
   var site_width = $('.site-width').eq(0);
   var elem = $('#current-prices');

   function toggle_block_on_resize(){
      site_width.width() > 1190 ? insertToIfIsNotSetInside(elem,1) : insertToIfIsNotSetInside(elem,2);
   }
   function insertToIfIsNotSetInside(elem,num){
      var elm_to = $('#js-box-for-courses-'+num);
      var elm = $('#current-prices', elm_to);
      !elm.length && elem.appendTo(elm_to);
   }
   toggle_block_on_resize();
   $(window).resize(toggle_block_on_resize);
});
//function showTRAIL IMG
var trailObj = {imgHeight:0,jqObj:$([])};
var trailMouseOffset = {left:50,top:0};

function showtrail(imagename,imgHeight,imagename2){
   trailObj.imgHeight = imgHeight;
   trailObj.jqObj = $('#trailimageid');
   str = '<img height="'+trailObj.imgHeight+'" src="' + imagename + '" border="0">';
   if(imagename2){
      str += '<span style="display:inline-block; width:10px; height:100%;">&nbsp;</span><img height="'+trailObj.imgHeight+'" src="' + imagename2 + '" border="0">';
   }
   trailObj.jqObj.html(str).stop(1).fadeTo(200,1);

   document.onmousemove=followmouse;
}

function hidetrail(){
   document.onmousemove="";
   trailObj.jqObj.stop(1).fadeTo(100,0,function(){$(this).css({left:"-1500px"});});
}

function getMousePosition(e){
   var position = {left:0,top:0};
   if(typeof e != "undefined"){
      position.left = e.pageX;
      position.top = e.pageY;
   }else if(typeof window.event != "undefined"){
      position.left = event.clientX;
      position.top = event.clientY;
   }
   return position;
}

function followmouse(e){
   var trailElemImg = $('img',trailObj.jqObj);
   var trailElemImgHeight = trailElemImg.height();
   if (!trailObj.imgHeight){
      trailObj.imgHeight = trailElemImg.height();
      trailElemImgHeight = trailObj.imgHeight;
   }
   var trailElemImgWidth  = trailElemImg.width();
   var trailCoord = {left:0,top:0};
   var mousePosition = getMousePosition(e);

   var docWidth = $(window).width();
   var docHeight = $(window).height();

   trailCoord.left = mousePosition.left + trailMouseOffset.left;

   var t_flag = docWidth - mousePosition.left < trailElemImgWidth + trailMouseOffset.left * 2 + 10;
   t_flag && (trailCoord.left = mousePosition.left - trailMouseOffset.left - trailElemImgWidth);

   trailCoord.top = (docHeight - trailElemImgHeight) / 2;

   var t = (docWidth < 1200) ? docWidth - 210 : docWidth / 2 + 390;
   if(mousePosition.left > t){
      trailCoord.left = t - trailMouseOffset.left - trailElemImgWidth;
      trailCoord.top = mousePosition.top;
   }

   trailObj.jqObj.css(trailCoord);
}
//END of function showTRAIL IMG


//-----------------------------------------------------------------------------------------CE
var isTestMode = 0;

function getBrowser(){
   var browserIs = new Object();browserIs.ie = 0;
   //browserIs.other=0;browserIs.ff = 0;browserIs.gc = 0;browserIs.op = 0;browserIs.sf = 0;
   if(IE='\v'=='v'){browserIs.ie = 1;}
   //else if(2){browserIs.ff=1;}	else if(3){browserIs.gc=1;}	else if(4){browserIs.op=1;}	else if(5){browserIs.sf=1;}	else{browserIs.other=1;}
   testing && console.log('browser: ie='+browserIs.ie/*+', ff='+browserIs.ff+', gc='+browserIs.gc+', op='+browserIs.op+', sf='+browserIs.sf*/);
   $(function(){!browserIs.ie && $('body').addClass('browser-is-ie');});
   return browserIs;
}
var browserIs = getBrowser();
function GlobalFunction(testing){
   this.test=testing;
}GlobalFunction.prototype={
   isSetTrue : function(a){return ((typeof(a)=='string' || typeof(a)=='number'||typeof(a)=='boolean')&&(a!='false'&&a!=0&&a!='0'&&a!=''))?1:0;},
   isFunc : function(f){return typeof(f)=='function'?1:0},
   isSet : function(a){return (typeof(a)!='undefined'&&a!=null)?1:0;},
   isResized : function(o){
      if(!this.isSet(o.data('widths'))){
         this.a('1');
         o.data('widths',0);
      }else{
         var w=o.width();
         var t=(o.data('widths') != w)?1:0;
         t&&o.data('widths',w);
         this.a('resized is "'+t+'"');
         return t;
      }
   },
   a : function(a){browserIs.ie && this.test&&console.log(a);},
   addElemCloneTo : function(elem,elemTo,func){
      var element = elem.clone(1,1).appendTo(elemTo);
      this.isFunc(func) && func(element);
      return element;
   }
}
var _GLOBAL_F = new GlobalFunction(isTestMode);
function Element(name,b,flagSet,func){
   this.name=name;
   this.selector=(b.selector?b.selector:'.')+name;
   this.active=(b.active?b.active:'');
   this.jq=null;

   _GLOBAL_F.isSetTrue(flagSet) && setJq();
   _GLOBAL_F.isFunc(func)&&func();
}Element.prototype={
   getClass : function(str){
      return '.'+this.name;
   },
   getId : function(str){
      return '#'+this.name;
   },
   setJq : function(e){
      if(_GLOBAL_F.isSet(e)){
         this.jq=e;
      }else{
         var self = this;
         this.jq=$(self.selector);
      }
   }
}

var testing = 0;//mode
var num_f = 0;//for console log
function ceSecureConst(){
   var t = new Object();
   t.BIND = 'addEvent';
   t.UNBIND = 'delEvent';
   t.DISABLED = 'disabled';
   t.ENABLED = 'enabled';
   t.SET = 'set';
   t.STATE = 'state';
   t.WITH = 'with';
   t.ADD_PLACEHOLDER = 'placeholder';
   t.INIT = 'init_ce';
   return t;
}
var ce_s = new ceSecureConst();
function CustomElem(str_elem){
   this.PREFICS = 'ce';
   this.FormElm = (str_elem!='select') ? 'input' : str_elem ;
   this.CEClass = '.'+this.PREFICS+'-'+str_elem;
   this.ceACTIVE = this.PREFICS+'-active';
   this.dataCell = this.PREFICS+'Set';
   this.dataVal = 1;
   this.ceDISABLED = this.PREFICS+'-disabled';
   this.speedOfFade = 300;
   this.disabledFadeTo = 0.2;
   this.TextElm = '.ce-t';
   var self = this;
   $(function(){testing && self.forTest()});
}CustomElem.prototype = {
   getFelm : function(jq_obj){
      var self = this;
      return (jq_obj.is(self.FormElm)) ? jq_obj : jq_obj.find(self.FormElm);
   },
   getCelm : function(jq_obj){
      var self = this;
      return (jq_obj.is(self.CEClass)) ? jq_obj : jq_obj.closest(self.CEClass);
   },
   disabled : function(jq_elem,func){
      var self = this;
      !browserIs.ie && jq_elem.fadeTo(self.speedOfFade,self.disabledFadeTo);
      jq_elem.addClass(self.ceDISABLED);
      jq_elem.find(self.FormElm).attr('disabled','disabled');
      if(typeof(func)=="function"){func();}
      testing && self.a('mode "disabled", length: ' + jq_elem.length);
   },
   enabled : function(jq_elem,func){
      var self = this;
      jq_elem.removeClass(self.ceDISABLED);
      !browserIs.ie && jq_elem.fadeTo(self.speedOfFade,1);
      jq_elem.find(self.FormElm).removeAttr('disabled');
      if(typeof(func)=="function"){func();}
      testing && self.a('mode "enabled", length: ' + jq_elem.length);
   },
   isSetData:function(jq_elem){
      return (jq_elem.data(this.dataCell) == this.dataVal);
   },
   setData:function(jq_elem){
      var self = this;
      jq_elem.each(function(){
         $(this).data(self.dataCell,self.dataVal);
      });
      return jq_elem;
   },
   isDisabled:function(jq_elem){
      return this.getFelm(jq_elem).is(':disabled');
   },
   //secure functions
   str_pad:function(str,finishLen,str_pad,pad_type){
      str_pad = typeof(str_pad) == 'string'  ? str_pad : ' ';
      pad_type = typeof(pad_type) == 'number' ? pad_type : 1;
      var t = str + '';
      var toggler = false;
      var len = Math.abs(finishLen - t.length);
      for(var i=0; i < len; i++){
         if(pad_type == 0){

            if(toggler) {
               t = str_pad + t;
            }else{
               t = t + str_pad;
            };
            toggler = !toggler;
         }else if(pad_type<0){
            t = str_pad + t;
         }else{
            t = t + str_pad;
         }
      };
      return t;
   },
   ceLog : function(some){
      var t1 = this.str_pad('#'+(++num_f),6);
      var t2 = this.str_pad(this.CEClass,15,' ',1);
      console.log(t1+'| '+t2+'| '+some);
   },
   forTest : function(){
      var self = this;
      if(self.CEClass != '.ce-input' && self.CEClass != '.ce-select'){
         $(self.CEClass + ' ' + self.FormElm ).show().css({position:'absolute',right:'-4px',top:'-4px',opacity:'0.5 !important'});
      }
      if(self.CEClass == '.ce-select'){
         $('.ce-select ' + self.FormElm).css({opacity:'0.5 !important'});
      }
      if(self.CEClass == '.ce-input'){
         $('.ce-input ' + self.FormElm).css({outline:'1px solid #ff0000 !important'});
      }
      //$(self.CEClass).css({outline:'1px solid #ffcc00'})
      self.ceLog('length = ' + $(self.CEClass + ' ' + self.FormElm ).length);
   },
   a : function(message){
      var flag = typeof(message) == 'boolean' || typeof(message) == 'number' || typeof(message) == 'string';
      message = typeof(message) ? message : 'TEST';
      this.ceLog(message);
   }
};
function CustomSelect(){
   var t = new CustomElem('select');
   t.switchText = function(jq_elem){
      t.getCelm(jq_elem).find(t.TextElm).text(jq_elem.find('option:selected').text());
      testing && t.a('set "'+jq_elem.find('option:selected').text()+'"');
   };
   return t;
};
var ce_select = new CustomSelect();
$.fn.ceSelect = function(mode){
   var c_elem = ce_select.getCelm(this);
   var f_elem = ce_select.getFelm(this);
   if(mode == ce_s.DISABLED){
      ce_select.disabled(c_elem,function(){
         c_elem.ceSelect(ce_s.UNBIND);
      });
   }else if(mode == ce_s.ENABLED){
      ce_select.enabled(c_elem,function(){
         c_elem.ceSelect(ce_s.BIND);
      });
   }else if(mode == ce_s.BIND){
      f_elem.bind('change',function(){
         ce_select.switchText($(this));
      });
      f_elem.bind('focus',function(){
         $(this).closest('.ce-select').addClass('ce-select-focus');
      });
      f_elem.bind('blur',function(){
         $(this).closest('.ce-select').removeClass('ce-select-focus');
      });
      f_elem.bind('keypress',function(){
         ce_select.switchText($(this));
      });
   }else if(mode == ce_s.UNBIND){
      f_elem.unbind('change');
      f_elem.unbind('keypress');
      f_elem.unbind('focus');
      f_elem.unbind('blur');
   }else if(mode == ce_s.SET){
      c_elem.ceSelect(ce_s.BIND);
      c_elem.each(function(){
         ce_select.switchText($(this));
         ce_select.isDisabled($(this)) ? $(this).ceSelect(ce_s.DISABLED) : null;
      });
   }else if(typeof(mode) == 'undefined'){
      c_elem.ceSelect(ce_s.SET);
   }else{
      f_elem.val(mode);
      c_elem.each(function(){
         ce_select.switchText($(this));
      });
   }
   return this.each(function(){});
};

$(function(){
   $('.ce-select').ceSelect();
});
