
// Cufon.replace('h1'); // Works without a selector engine
// Cufon.replace('.t'); // Requires a selector engine for IE 6-7, see above

var lightOpen, lightClose, lightMove, showPopupAd;

var hei;


$(function() {

    hei = $("body").height();
    lightboxCheck();
    initBinding();


    function lightboxCheck() {

      // For each image
      $('span.img-polaroid').each(function() {

        // If the image has a class of 'zoom' and the previos element doesn't have a 'caption' class
        if($(this).next().attr('class') == 'zoom' && $(this).prev().attr('class') !== 'caption') {

          $(this).css('cursor', 'pointer')
          $(this).addClass('lightbox');
          $(this).parent().prepend('<span class="caption"></span>');

        }

      });

    }

    function initBinding() {
      $('span.img-polaroid').hover(function() {

        if($(this).prev().css('opacity') == '0') {

          $(this).prev().fadeTo('500', '0.6');

        }

      }, function() {

        $(this).prev().fadeTo('500', '0');

      });

      $('span.img-polaroid').click(function() {

        // When clicked on the span tag before the 'a' element, click on the anchor tag
        if($(this).next().attr('class') == 'zoom') {

          $(this).next().click();

        }

      }).first().each(function(){
          setTimeout(
            function()
            {
              if (typeof is_main == "undefined") $("body").height(hei);
            },
            500
          );
      });

    }

    $('div.slider').sliders({

      cycle : true, // true or false
      slideWidth : 980, // width per slide
      cycleInterval : 5000 // pause in milleseconds between animation

    });

    $('div.portfolio-slider').sliders({

      cycle : true, // true or false
      cycleInterval : 8000, // pause in milleseconds between animation
      arrowNavigationWrapper : 'div.portfolio-slider', // wrapper class
      slideWidth : 310, // width per slide
      projectSlider : true, // true or false
      sliderdots : false // true or false

    });

    // Get the position of the contact form
    var position = $('#contact').position();

    // When clicked on 'add comment' or 'reply' button
    $('a.add-comment, a.reply').click(function(e) {

      // Don't go to the top
      e.preventDefault();

      // Animate screen to top of the contact form
      //$('html, body').animate({scrollTop: position.top}, 300);

    });

    // =======================================================================
    // My Lightbox
    // =======================================================================
    
    var lightIsOpened = false, lightSpeed = "normal";
    
    lightOpen = function(x, y, content)
    {
      var worker = function()
      {
        $("#my_lightbox")
          .css("width", x)
          .css("height", y)
          .css("left", Math.floor(($(window).width() - x - 60) / 2))
          .css("top", $(document).scrollTop() + Math.floor(($(window).height() - y - 60) / 2))
          .fadeIn(lightSpeed, function()
          {
            $("#my_lightbox_close").click(function(ev)
            {
              ev.preventDefault();
              lightClose();
            });

            lightIsOpened = true;
          });
        $("#my_lb_content").html(content);
      }
      
      if (lightIsOpened)
      {
        $("#my_lightbox").fadeOut(lightSpeed, worker);
      }
      else
      {
        $("#gray_bg")
          .css("width" , $(document).width())
          .css("height", $(document).height())
          .click(lightClose)
          .fadeIn(lightSpeed, worker);
      }
    }
    
    lightClose = function()
    {
      if (!lightIsOpened)
      {
        return;
      }
      
      $("#my_lightbox").fadeOut(lightSpeed, function()
      {
        $("#my_lightbox_prev").css("display", "block");
        $("#my_lightbox_next").css("display", "block");
        $("#gray_bg").fadeOut(lightSpeed);
      });
      
      lightIsOpened = false;
    }
    
    // =======================================================================
    // Lightbox replacement
    // =======================================================================
    
    var photos = {}, photoPtr = {}, curHash;
    
    function lightRegister(objs, hash, renderer, onclick)
    {
      onclick = onclick || function(obj, id)
      {
        var data = renderer(obj, id);
        lightOpen(data.width, data.height, data.content);
      }
      
      if (typeof photos[hash] == "undefined")
      {
        photos[hash]        = [];
        photoPtr[hash]      = 0;
        $(objs).each(function()
        {
          photos[hash].push(this);
          var photoId = photos[hash].length - 1;
          
          $(this)
            .click(function(ev)
            {
              ev.preventDefault();
              photoPtr[hash] = photoId;
              curHash = hash;
              onclick(this, photoId);
            });
        });
      }
    }
    
    lightMove = function(delta)
    {
      photoPtr[curHash] += delta;
      
      if (photoPtr[curHash] < 0)
      {
        photoPtr[curHash] = photos[curHash].length - 1;
      }
      else if (photoPtr[curHash] >= photos[curHash].length)
      {
        photoPtr[curHash] = 0;
      }
      
      $(photos[curHash][photoPtr[curHash]]).click();
    }
    
    // --- Register prettyPhotos handler -------------------------------------
    
    lightRegister(
      $("a[rel^='prettyPhoto']"),
      "prettyPhoto",
      function() {},
      function(obj)
      {
        var
          img = new Image(),
          ttl = $(obj).attr("title"),
          id  = $(obj).attr("id").toString().replace(/\D/g, ""),
          alt = $("img:first", obj).attr("alt");
        
        if (typeof keywInfo != "undefined")
        {
          $("a#keyw_" + id).click();
          return;
        }
        
        img.onload = function()
        {
          var text = "<div style=\"padding: 46px 0\"><img src=\"" + img.src
                   + "\"></div><div class=\"prettySub\"><a href=\"" + alt
                   + "\" target=\"_blank\">" + ttl + "</a></div>";
          
/*          if (typeof keywInfo != "undefined")
          {
            text += "<div class=\"prettyKeyw\"><a href=\"/portfolio/category/2/"
                  + ttl + "/\" onclick=\"$(&quot;a#keyw_" + id
                  + "&quot;).click(); return false\">Ключевые слова (" + keywInfo[id].num + ")</div>";
          }*/
          
          lightOpen(
            img.width,
            img.height + 92,
            text
          );
        }
        
        img.src = $(obj).attr("href");
      }
    );
    
    // --- Register clients' opinions handler --------------------------------
    
    lightRegister(
      $("#clients_photo a"),
      "clients_photo",
      function(obj, id)
      {
        var data = clients_info[$(obj).attr("rel").toString()];
        
        var out = {
          "width"  : 920,
          "height" : 450,
          "content": "<table cellspacing=\"0\" class=\"client_info\"><tr><th><img src=\"" + $(obj).attr("href") +  "\" width=\"450\" height=\"450\" /></th><td><p><b>" + data.fio + "</b></p><p>" + data.post + "</p><p><a href=\"http://" + data.site + "/\" target=\"_blank\">" + data.site + "</a></p><br />" + data.review + "</td></tr></table>"
        };
        
        return out;
      }
    );
    
    // --- Register SEO portfolio handler ------------------------------------
    
    lightRegister(
      $("a.keywords"),
      "keywords",
      function() {},
      function(obj)
      {
        var id = $(obj).attr("rel").toString();
        
        $.get(
          $(obj).attr("href"),
          function(data)
          {
            info = keywInfo[id];
            
            lightOpen(
              900,
              360,
              "<div class=\"keyw_tabs\">Ключевые слова &nbsp;&nbsp; <a href=\"#\" onclick=\"$(&quot;#vis_" + id + "&quot;).click(); return false\">Видимость сайта</a></div><table cellspacing=\"0\" class=\"keyw_table\"><th><img src=\"" + info.screen + "\" width=\"480\"/></th><td><p><a href=\"http://" + info.link + "/\" target=\"_blank\">" + info.link + "</a></p><div class=\"keyw_cont_1\"><div class=\"keyw_cont_2\">" + data + "</div></div></td></table>"
            );
          }
        );
      }
    );

    lightRegister(
      $("a.visibility"),
      "visibility",
      function() {},
      function(obj)
      {
        var id = $(obj).attr("rel").toString();
        
        info = keywInfo[id];
        
        lightOpen(
          900,
          360,
          "<div class=\"keyw_tabs\"><a href=\"#\" onclick=\"$(&quot;#keyw_" + id + "&quot;).click(); return false\">Ключевые слова</a> &nbsp;&nbsp; Видимость сайта</div><table cellspacing=\"0\" class=\"keyw_table\"><th><img src=\"" + info.screen + "\" width=\"480\"/></th><td><p><a href=\"http://" + info.link + "/\" target=\"_blank\">" + info.link + "</a></p><div class=\"keyw_cont_1\"><div class=\"keyw_cont_2\"><div id=\"fgraph_inner_" + id + "\"></div></div></div></td></table>"
        );
        
        setTimeout(
          function()
          {
            swfobject.embedSWF(
              "/media/open-flash-chart.swf",
              "fgraph_inner_" + id,
              "100%",
              "250",
              "9.0.0",
              "expressInstall.swf",
              {
                "data-file": "/stats/project_graph_data/" + id,
                "loading": "Загрузка данных диаграммы..."
              }
            );
          },
          1000
        );
      }
    );

    // --- Register online order popup handler -------------------------------
    
    lightRegister(
      $("a#order_online"),
      "order_online",
      function() {},
      function(obj)
      {
        var rel = $(obj).attr("rel");
        
        $.get(
          "/servises/ajax/" + (rel ? rel : "1") + "/",
          function(data)
          {
            $("#my_lightbox_prev").css("display", "none");
            $("#my_lightbox_next").css("display", "none");
            
            lightOpen(
              700,
              680,
              "<table cellspacing=\"0\" style=\"position: relative; top: 30px\"><tr><td style=\"width: 700px; height: 650px; vertical-align: bottom\">" + data + "</td></tr></table>"
            );
          }
        );
      }
    );
    
    showPopupAd = function()
    {
      var top = Math.round(($(window).height() - 379) / 2);
      
      $("#popup_ad")
        .fadeIn()
        .css("left", Math.round(($(window).width() - 700) / 2) + "px")
        .css("top", (top + $(window).scrollTop()) + "px");
      $(window).scroll(function(ev)
      {
        $("#popup_ad").css("top", (top + $(window).scrollTop()) + "px");
      });
      $("#popup_ad_close").click(function(ev)
      {
        ev.preventDefault();
        $("#popup_ad").fadeOut();
      });
    }
      
    var anc = document.location.href.match(/#(.+)$/);
  
    if (anc !== null && anc.length > 1)
    {
      //alert(anc[1]);
      $("a[rel=\"" + anc[1] + "\"]").click();
    }

  
  
});




