$(document).ready(function () {	

    if (typeof(TravelSearch)!='undefined' && TravelSearch.autosearch){TravelSearch.searchHotel();}  

    $("input[id*=close]").click(function(){$.modal.close();});

    $("img[id*=showimg__]").mouseover(function () {
        $(this).css("cursor","pointer");
    });

    $("img[id*=showimg__]").click(function () {
    var value=$(this).attr("id").split('__');
    if (value[3]){
      $("#showimg").attr("src",fileroot+"/"+value[1]+"/"+value[3]+"/photos/"+value[2]); 
    }
    else 
      $("#showimg").attr("src",fileroot+"/"+value[1]+"/photos/"+value[2]); 
	  });


    $(".showthumb").click(function () {
       $("#showthumb img").attr("src",$(this).attr("src").replace("thumb/","")); 
    });

    $("#travel .thumb").slowEach(15000, function () {
      var value=$(this).attr("id").split('__');
      $("#showimg").fadeOut().attr("src",fileroot+"/"+value[1]+"/photos/"+value[2]).fadeIn("slow");
    });

    $(".hbox").mouseover(function () {
      $(this).css('border','1px solid #fa6400');
    });

    $(".hbox").mouseout(function () {
      $(this).css('border','1px solid #ccc');
    });

    $(".intxt").focus(function () {
  		$(this).css("border","1px solid #990000").css("color","#000");
  	});

    $(".intxt").blur(function () {
  		$(this).css("border","1px solid #BBBBBB").css("color","#606060");
  	});
    
    if (typeof(id)!='undefined' && id>0){
      $.getJSON("/../data.php?action=makePopular&pagetype="+pagetype+"&etis="+etis+"&domain="+domain+"&nid="+id+"&type="+type, function(json){});
    }
     
    $('.link_friend').click(function(){$("#friendWindow").html(makeFriendForm()).modal();return false;});  
    $('.link_book').click(function(){$("#bookWindow").html(makeBookForm()).modal();});
    $('.link_request').click(function(){$("#requestWindow").html(makeRequestForm()).modal();return false;});   
    
    $('#searchword').click(function(){searchDream();});
    $('#commentLink').click(function(){$("#commentWindow").html(makeCommentForm()).css("visibility","visible");return false;});
    $('#commentWindow input').keypress(function(event) {$(this).css("border","1px solid #aaa");});

    $(".reply_option").click(function(){BBCode.setBBCode("fld_text", $(this).attr("id"));}); 
   
    $('#story_save').click(function(){Stories.saveStory();});
    
    $("#smilies img").click(function(){Smilies.setBBCode("fld_text", $(this).attr("src"));});

    $(".mailimg").click(function(){activateMail($(this).attr("id"));});     
    
    if (typeof(travelobj)!='undefined'){
      TravelObjects.load();
    }   

    if (typeof(traveloffer)!='undefined'){
      TravelOffer.load();
    }   

    if (typeof(myopinions)!='undefined'){
      MyOpinions.load();
    }   

     
    $("#county_id").change(function(){
        getCityData('county_id', 'city_id', document.getElementById("city_id"));
    });

    $("#country_id").change(function(){
        getCityData('country_id', 'county_id', document.getElementById("county_id"));
    });

    $("#city_id").change(function(){
        getCityData('city_id', 'region_id', document.getElementById("region_id"), 'region');
    });

    $("#ad_rubric_id").change(function(){
       getCatForRubric(''); 
    });        

    if (typeof(imot_edit)!='undefined'){
     if (typeof(art)!='undefined'){
       if(art == 81){
         $('#building').attr("class","blockdisp");
       } else if (art > 76){
         $('#land').attr("class","blockdisp");
       } else if (art < 76 && art > 0){
         $('#building').attr("class","blockdisp");
       }
      }
    } 
         
    $("#art").change(function () {
      var value = $("#art").attr("value"); 
      checkType(value);
    });

    $("#a16").click(function(){
        checkA16();
    });

    
    if (typeof(city_id)!='undefined' && city_id >0){
      getCityData('county_id', 'city_id', city_id);
    }

          $("a[id*=prioasc]").click(function(){
             var value = $(this).attr('id').split('_');
             Prio.putPrio('data.php','putPrio', 'pid', value[1], value[2], 'asc',  value[3]);
             return false;
          });
  
          $("a[id*=priodesc]").click(function(){
             var value = $(this).attr('id').split('_');
             Prio.putPrio('data.php','putPrio', 'pid', value[1], value[2], 'desc', value[3]);
             return false;
          });
  
    if (typeof(load_date)!='undefined' && load_date >0){
	   $('.date-pick').datePicker({startDate:'01/01/1996'});
    }
    
    $("#nextarr,#prevarr, #mytop .tabs a").click(function(){
      var slide = $(this).attr("id");
      if (typeof(Slider) == 'undefined'){
        $.getScript("/js/my/slider.js", function(){
          Slider.load(slide);
        }); 
      } 
    }); 
  
   $('.rating').bind('mousemove', function(e) {animateRating(e, '.rating', $(this).attr('id'));});
   $('.rating').click(function(e) {vote(e, $(this).attr('id'));});
   $('.print').click(function(){window.print();return false;});
   $('.ifb').click(function(){fbs_click();});
   $('.itweet').click(function(){
    tw_click($(this).attr("title"));
   });

   if (typeof(fancybox) != 'undefined' && fancybox != ''){
     $(".fbox").fancybox({
       'autoScale'   : true,
   		 'transitionIn'		: 'none',
   		 'transitionOut'		: 'none',
     	 'scrolling'       : 'no',
  		 'showCloseButton'	:	false
  	 });
   }

   if (typeof(Spot) != 'undefined'){
      $.getScript("/js/classes/setme/set" + etis + ".js", function(){
        var spot = new Spot();
        spot.init();
      }); 
   }

   if ($(".waypoints").length || $(".titlenav").length){
    $.getScript("/js/classes/slider.js", function(){
      var slider = new Slider();
      slider.init();
    }); 
   }

   if (typeof(MyArticles) != 'undefined'){var ma = new MyArticles();}
   if (typeof(MyLibPics) != 'undefined'){var mlp = new MyLibPics();}
   if (typeof(MyLibOrder) != 'undefined'){var mlo = new MyLibOrder();}
   if (typeof(WriteMe) != 'undefined'){var wm = new WriteMe();}

});


animateRating = function(e, identifier, myid){

  var identifier = (typeof(myid) != 'undefined') ? '#' + myid : identifier;
  var offset     = $(identifier).offset();
  var x = Math.round((e.pageX - offset.left)/20.8);
  $(identifier).removeClass("s0 s1 s2 s2 s3 s4 s5").addClass("s" + x);
  return x;
};


vote = function(e, myid){

  var identifier = (typeof(myid) != 'undefined') ? '#' + myid : '.rating';
  var value = animateRating(e, identifier);
  $.ajax({
    cache: false,
    timeout: (2000),
    dataType: 'json',
    url: '/../data.php?action=vote&id=' + id + '&typ=' + type + '&pagetype=' + pagetype + '&rating=' + value,
    success: function(json){
      if (parseInt(json)>0){
        $('.rating').addClass("sprit itick mt2").removeClass("s0 s1 s2 s2 s3 s4 s5 rating");
        $('.votes').css('display','none');
      }
    }
  });
};


activateMail = function(newid){
 var parts = newid.split("_");
 var v = ($("#"  + newid + " img").attr("src") == '/files/icons/tick.png')?0:1;
          
 $.getJSON("/../data.php?action=" + action + "&id=" + parts[1] + '&v=' + v, function(json){
  if (json.Result){
   var img = (json.Data == 1)?'tick':'cancel';
   $("#" + newid + " img").attr("src","/files/icons/" + img + ".png");           
  } 
 });
};





// set link to id node
setLink = function(src, prefix, id, title){

  var l = '/' + prefix + '-' + id;
      l += (title)?'-' + title.replace(/\s/g, "_"):''; 

      if ($("#" + src).is(":visible")){
       $("#" + src).attr("href", l);
       $("#" + src).attr("title", title);
      }
  return false;
};


stripslashes = function(str) {
    str=str.replace(/\\'/g,'\'');
    str=str.replace(/\\"/g,'"');
    str=str.replace(/\\\\/g,'\\');
    str=str.replace(/\\0/g,'\0');
    return str;
};



$.postJSON = function(url, data, callback) {
	       $.post(url, data, callback, "json");
};



jQuery.fn.slowEach = function( interval, callback ) {
        var array = this;
        if( ! array.length ) return;
        var i = 0;
        next();
        function next() {
            if( callback.call( array[i], i, array[i] ) !== false )
                if( ++i < array.length )
                    setTimeout( next, interval );
        }
}; 



searchDream = function(){
  var value=$('#searchtext').val();
  var url="/../data.php?action=findWord&value="+encodeURIComponent(value)+"&value2="+value;
  $('#results').html('<div class="c_red bold ml10 mt15"></div>');
                      
  $.getJSON(url, function(json){
   if (json.Result){
     var text=''; 
     var counter=0; 
 
     for (j in json.Data){
      counter++; 
      if (counter==1){
       text+="<ul class=\"no_dist ml15 pl10\">";
      }
      text+="<li class=\"pt10\"><a href=\"/l-"+json.Data[j].Dream_id+"-"+json.Data[j].Title.replace(" ","_")+"\">"+json.Data[j].Title+"</a></li>";
     }
 
     if (counter>0){
      text+="</ul>";
     } else {
      text+="<h4 class=\"mt5 ml10 c_red\">"+json.No_results+"</h4>"; 
      text+="<ul class=\"no_dist ml15 pl10\">";
      text+="<li class=\"pt5\">"+json.Results_text1+"</li>";
      text+="<li class=\"pt5\">"+json.Results_text2+"</li>";
      text+="<li class=\"pt5\">"+json.Results_text3+"</li>";
      text+="</ul>";
     }
                       
     if (json.Data2){ 
      text+="<h3 class=\"mt15 pt5 ml10 \">"+json.Results_text+" '"+json.Word+"'</h3>"; 
      text+="<ul class=\"no_dist ml15 pl10\">";
      for (k in json.Data2){
       text+="<li class=\"pt10\"><a href=\"/l-"+json.Data2[k].Dream_id+"-"+json.Data2[k].Title.replace(" ","_")+"\">"+json.Data2[k].Title+"</a></li>";    
      }
      text+="</ul>";
     }
     $('#results').html(text);
   } else alert(json.Text);
  });
};


logout = function(){
$.getJSON("/../data.php?action=doLogout&user="+user, function(json){
 if (json.Result == true){
  window.location.reload();
  }
 });
};



function getMetrics() {

 $.ajax({
   type: "GET",
   data: {
    action: 'getMetrics'
   }, 
   url: '/../data.php',
	 dataType: 'json',
	 timeout: 6000,
	 global: 'false',
	 success: function(json) {
   if (json.Result){
    var text= "<span class=\"c_red mr5\">"+json.Data['Hi']+' '+json.Data['User']+ "</span> [ <a href=\""+loginurl+"\">"+json.Data['Admin']+"</a> ] [ <a href=\"#\" onClick=\"logout();\">"+json.Data['Logout']+"</a> ] ";
    if (if_exists(document.getElementById('comment_name')) && json.Data['User'] && json.Data['User']){
      $("#comment_name").css("display","none");
      $("#cuser").html(json.Data['User']);    
     }
    } else {
     var text=today+" [ <a href=\""+loginurl+"\">"+json.Data['Login']+"</a> ]";
    } 
    $("#hline").html(text);    
   }
 });  
};


  
hideComment = function(){
 $("#commentWindow").text("").css("visibility","hidden");
 $("#commentLink").css("visibility","visible");
};



sendComment = function(){
     $("#comment_msg").html('');
     $.ajax({
		          type: "POST",
		          data: {
                     action: 'sendComment',
                     id: id,
                     type: contenttype,
                     title: $("#comment_subject").val(),
                     description: $("#comment_text").val(),
                     name: $("#comment_name").val(),
                     stars: $("#comment_stars").val(),
                     art: art,
                     cache: cache,
                     captcha: $("#comment_captcha").val()
                    },
              url: '/../data.php',
		          dataType: 'json',
		          timeout: 602222,
		          global: 'false',
		          success: function(json) {
               if (json.Result>0){
                $("#comment_msg").html(json.Text);
                $("#comment_body").css("display","none");
               }else{
                $("#comment_msg").html(json.Text).css("color","#ff0000");
                if (json.Selected){
                  $("#" + json.Selected).css("border","1px solid #ff0000").focus();
                }
               }
             }    
          });  
};

 
function nl2br(str) {
 if(typeof(str)=="string") 
  return str.replace(/(\r\n)|(\n\r)|\r|\n/g,"<BR>");
 else return str;
};
 
 
function if_exists(obj){
 return typeof(obj)!='undefined';
};

function fbs_click() {
    window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(location.href)+'&t='+encodeURIComponent(document.title),'sharer','toolbar=0,status=0');
    return false;
};

function tw_click(title) {
    window.open('http://twitter.com/intent/tweet?text=' + title + '&url='+encodeURIComponent(location.href),'tweeter','toolbar=0,status=0');
    return false;
};

  function checkCity(region_id){
      var elem=document.getElementById("city_id"); 
      if (elem.selectedIndex>0){
        getCityData('city_id', 'region_id', region_id, "region_div");
      }
  }
 
  function getCityData(fieldFrom, fieldTo, fieldToValue, showdiv)
  {
    
      if (!$("#" + fieldTo).length > 0){
        return false;
      }
      
      var elementFrom = document.getElementById(fieldFrom); 
      var elementTo = document.getElementById(fieldTo); 
      elementTo.options.length = 0;
      
      
      $.getJSON("/../data.php?action=getCityData&"+fieldFrom+"="+elementFrom.options[elementFrom.selectedIndex].value, function(json){
          
          var counter=1; 
          if (json){
              if (json.iso == 'en'){
                var choose="--- Choose ----";
                var choose_district="---Choose district first ----";
              } else {
                var choose="--- Избери ----";
                var choose_district="---Избери Област първо----";
              }
            
              elementTo.options[0]=new Option(choose,'');

              for (j in json.elements){ 
               if (parseInt(j) > 0){
                 elementTo.options[counter]=new Option(json.elements[j],j);
                 if (fieldToValue==j){
                   elementTo.selectedIndex=counter;           
                 }
                 counter++;
               }
              }
          } else elementTo.options[0]=new Option(choose_district,'');
      
          

         if (counter>1){ $("#"+showdiv).css("display","inline"); }    
         else { $("#"+showdiv).css("display", "none"); }
          
       });
  }
  
  
    
getCatForRubric = function(ad_cat_id)
{ 
   var elementFrom=document.getElementById("ad_rubric_id");
   var elementTo=document.getElementById("ad_cat_id");
   elementTo.options.length = 0;
         
   $.getJSON("data.php?action=getAdCategory&ad_rubric_id="+elementFrom.value, function(json){
              
   var counter=1; 
   if (json.Arr){
     elementTo.options[0]=new Option('--- Избери ----','');
     for (var j=0; j<json.Arr.length; j++){  
       elementTo.options[counter]=new Option(json.Arr[j].Name_bg,json.Arr[j].Ad_cat_id);
       counter++;
       if (ad_cat_id==json.Arr[j].Ad_cat_id){
         var index= j+1; 
         elementTo.selectedIndex=index;           
       }
     }
   } else 
     elementTo.options[0]=new Option('--- Избери рубрика първо ----','');
   });
};  



checkRubric = function(ad_cat_id){
 var elem=document.getElementById("ad_rubric_id"); 
 var id=ad_cat_id; 
 if (elem.selectedIndex>0){
   getCatForRubric(id); 
 }
}

function scrollTop() {
	return filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
};

function filterResults(n_win, n_docel, n_body) {

	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
};



strip_tags = function (strMod) {

    if(arguments.length<3) 
        strMod=strMod.replace(/<\/?(?!\!)[^>]*>/gi, '');
    else{
        var IsAllowed=arguments[1];
        var Specified=eval("["+arguments[2]+"]");

        if(IsAllowed){
            var strRegExp='</?(?!(' + Specified.join('|') + '))\b[^>]*>';
            strMod=strMod.replace(new RegExp(strRegExp, 'gi'), '');
        }else{
            var strRegExp='</?(' + Specified.join('|') + ')\b[^>]*>';
            strMod=strMod.replace(new RegExp(strRegExp, 'gi'), '');
        }
    }
    return strMod.replace("  "," ");
};  


in_array = function(arr, needle) {
  for(var i=0; i < arr.length; i++) if(arr[i] === needle) return i;
  return false;
};


//format number
String.prototype.substr_word = function(size){

  var newtext = this.substr(0,size);
  for (var i=newtext.length-1;i>=0;i--){
    if (newtext.charAt(i)!=' '){
      newtext =  newtext.substr(0,i);    
    } else {
      newtext = newtext.substr(0,i);    
      break; 
    }
  }  

  return newtext;
};



function fillSelected(id, value){

      var size=document.getElementById(id).length;
      for(i=0;i<size;i++)
      {
        if(document.getElementById(id).options[i].value==value)
        {
            document.getElementById(id).selectedIndex=i;
        }
      }
}

addPreload = function(id, newClass, art){
  $(id).html('<p class="' + ((typeof(newClass)!='undefined') ? newClass : '') + ' preload"><img src="' + piclib + '/' + ((typeof(art)!='undefined')?art:'preloader.gif') + '" /></p>');
};
