jQuery.extend(jQuery.validator.messages, {
     required: "Ovo polje je obavezno!",
     email: "Molimo unesite ispravnu email adresu!"
});


(function($){
  $.fn.fp = function ()
  {
    $(this).css({
      display: "block",
      clear: "both",
      padding: "1em 0",
      width: "600px",
      height: "350px"
    });
    flowplayer(this.get()[0], "/media/flowplayer.swf", {
      clip: {
        url: "/media/rave/skins/video/" + $(this).data('videosrc'),
        scaling: "fit",
        autoPlay: false,
        autoBuffering: true,
        bufferLength: 5,
        urlEncoding: true
      },
    });
  }
})($);

(function($){
  $.fn.fplive = function ()
  {
    $(this).css({
      display: "block",
      clear: "both",
      padding: "1em 0",
      width: "600px",
      height: "350px"
    });
    flowplayer(this.get()[0], "/media/flowplayer.swf", {

    	clip: {
    		url: $(this).data('name') || 'my_lifecast',
    		provider: 'rtmp'
    	},

    	plugins: {
    		rtmp: {
    			url: '/media/flowplayer.rtmp-3.2.3.swf',
    			netConnectionUrl: $(this).data('videolive')
    		}
    	}
    }); 
  }
})($);



var page = {
        tr: null, ts: null, Tracker: null, o: new Object,
        
        init: function() {
          if ($("[data-videosrc]").length) {
           $("[data-videosrc]").fp(); 
          }
          
          if ($("[data-videolive]").length) {
            $("[data-videolive]").fplive();
          }
          
          $("#commentForm").validate();          
          
          if ( $("#slider").length ) {
            var nav = $("div.navigation");
            nav.css({
              'display':"-moz-inline-stack",
              'display':"inline-block",
              'zoom':1,
              '*display':"inline"
            })
            page.tr = $("#slider").fadeTransition({pauseTime: 30000, transitionTime: 1000});
            nav.each(function() {
              $(this).children().each( function(idx) {
                if ($(this).is("a"))
                  $(this).click(function() { page.tr.showItem(idx); return false; })
              });
            });
          }
          
          if ( $("#ticker").length ) {
            $("#ticker").css('display', 'block');
              var options = {
                  newsList: "#novosti",
                  startDelay: 10,
                  placeHolder1: "_",
                  controls: false
              }
              $().newsTicker(options);       
          };
          
          if ( $("div#right_column").length ) {
            $('.tab_container').each(function(){ page.lists($(this).attr('id')); });
            page.facebookConnect();
          };
          
          if ($('div#social').length) {
            page.social();
          };          

          if ($("div#gallery").length) {
            page.gallery();
          };
          
          if ($('#gallery_period').length) {
            $('select#gallery_period').bind('change', function() {
              var q = $(this).val().split(",");
              if (q[1]) {
                $.get('/d/'+q[0]+'/'+q[1], function(data){
                 $('#gals ul').html(data);
                });
                
              };
            });
          }
          
          if ($("div#galerija").length){
            $(window).load(
              function(){
               var current = 1;
                $('div.roll').each(function(index) {
                  $(this).css('visibility','visible');
                  var img = $(this).find('img');
                  var w = img.width();
                  var h = img.height();
                  
                  img.css({'left':(792-w)/2});
                  img.css({'top':(600-h)/2});
                  
                  if (index == 0) { 
                    $(this).css({'display':'block'});
                  } else {
                    $(this).css({'display':'none'});
                  }
                });

                $(window).keydown(function(event){
                    var key = event.keyCode;
                    if (key == 37) {  $("#galerija .right").trigger('click'); };
                    if (key == 39) {  $("#galerija .left").trigger('click'); };
                });

                $("#galerija .left").bind('click', function(){
                  list('p');
                } );
                $('#galerija .right').bind('click', function(){
                  list('n');
                } );

                function list(q){
                  q == 'p' ? c=current+1 : c=current-1;
                  var x = $('div.roll:nth-child('+current+')');
                  var y = $('div.roll:nth-child('+c+')');
                  if (y.length != 0) {
                    current = c;
                  } else {
                    if (current == 1) {
                      var y = $('div.roll:nth-child('+$('div.roll').length+')');
                      current = $('div.roll').length;
                    } else {
                      var y = $('div.roll:nth-child(1)');
                      current = 1;
                    }
                  }
                  x.fadeOut();
                  y.fadeIn();
                }
              }
          );
          };
          
          page.googleAnalyze();
          
        },
        
        social: function(){
          
          var social = $('div#social'),
              t = document.title,
              u = "http://depo.ba/vijest/"+$('h2').attr('data-id'),
              short_t = $('p#short_description').text();
              
          var services = {
                          'digg':   {
                                      'url'   : "http://digg.com/submit",
                                      'link'  : "url",
                                      'title' : "title"
                          },
                          'facebook': { 
                                      'url'   : "http://www.facebook.com/share.php",
                                      'link'  : "u",
                                      'title' : "t"
                          },
                          'twitter': {
                                      'url'   : "http://twitter.com/home",
                                      'title' : "status"
                          },
                          'google': {
                                      'url'   : "http://www.google.com/bookmarks/mark",
                                      'link'  : "op=edit&bkmk",
                                      'title' : "title",
                                      'desc'  : "annotation"
                          },
                          'delicious': {
                                      'url'   : "http://delicious.com/post",
                                      'link'  : "url",
                                      'title' : 'title',
                                      'desc'  : 'notes'
                      }
          };
          
          $.each(services, function(i, v) {
            var link = document.createElement('a');
                if (v.link) {
                  q = v.link+"="+u+"&"+v.title+"="+t;
                  v.desc ? q+="&"+v.desc+"="+short_t : null;
                } else {
                  $(link).click(function(){
                    shortUrl(this.href);
                    return false;
                  });
                  q = v.title+"="+t;
                  v.desc ? q+=v.desc+"="+short_t : null;
                }
                
              
                link.href = v.url+"?"+q;
                $(link).addClass('social').addClass(i).text(i).appendTo(social);
          });
          
           function shortUrl(h){
             var u = 'http://beta.url.ba/api.php?url='+location.href+'&jsoncallback=?';
             $.getJSON(u, function(data) {
                h += ' → http://url.ba/'+data.short;
                location.href = h;
             });
           }
        },
        
        gallery: function(){
          
          //Preload images in gallery
          $("div#gallery ol li a").each(function(){
            var img = new Image;
                img.src = this.href;
          });
          
          $("div.left").bind('click', function(){
            $("div#gallery ol li:last").prependTo("div#gallery ol");
            $("div#gallery ol").css({"left":-115});
            $("div#gallery ol").animate({"left":0}, "fast");
            $("div#gallery ol li a").trigger('click');
          });
          
          $("div.right").bind('click', function(){
            $("div#gallery ol").animate({"left":-115}, "fast", function(){
              $("div#gallery ol").css({"left":0});
              $("div#gallery ol li:first").appendTo("div#gallery ol");
            });
            $("div#gallery ol li").next().find('a').trigger('click');
          });
          
          var img = $(document.createElement('img'));
          
          img.bind('click', function(){

              var expose = $(document.createElement('div'));
              var overlay = $(document.createElement('div'));
                  img_c = img.clone();
                  overlay
                    .html(img_c)
                    .addClass('overlay')
                    .bind('click', function(){
                      overlay.fadeOut('fast', function(){ $(this).remove(); });
                      expose.fadeOut('fast', function(){ $(this).remove(); });
                  })
                  .prependTo('body')
                  .fadeIn('slow')
                  .css({
                          "top":($(window).height()/2)-(img_c.height()/2)-20+"px",
                          "left":($(window).width()/2)-(img_c.width()/2)-20+"px"
                  });
                  

                  
                  expose
                    .addClass('expose')
                    .fadeIn('fast')
                    .bind('click', function(){
                      overlay.fadeOut('fast', function(){ $(this).remove(); });
                      expose.fadeOut('fast', function(){ $(this).remove(); });
                    })
                    .prependTo('body');
          });
          
          $(window).keydown(function(event){
              var key = event.keyCode;
              if (key == 37) {  $("div.right").trigger('click'); };
              if (key == 39) {  $("div.left").trigger('click'); };
              if ($('.overlay').length) {
                if (key == 27 || key == 13) {  $('.overlay').trigger('click'); };
                if (key == 37) {  $("div.right").trigger('click'); };
                if (key == 39) {  $("div.left").trigger('click'); };
              } else {
                if (key == 13) {  img.trigger('click'); };
              }
          });
          
          $("div#gallery ol li a").live('click', function(){
            var src = $(this).attr('href');
            var alt = $(this).attr('title');
                      
                      var new_image = new Image;
                          new_image.src = src;
                          $(new_image).load(function(){
                           img.parent().height(this.height+'px');
                          });
                      
            img.fadeOut('fast', function(){
              img.attr({'src':src, 'alt':alt});
              img.fadeIn('fast');
              img.parent().height(img.height()+10);
            });
            return false;
          });
          
          if ( !$("#picture_preview img").length ) {
            img.attr({'src':$("div#gallery ol li a").attr('href'), 'alt':$("div#gallery ol li a").attr('title')});
            $("#picture_preview").html(img);
          };
        },
        
        googleAnalyze: function(){
          var host = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
          var src = host + 'google-analytics.com/ga.js';
          $.ajax({
            url: src,
            type: 'GET',
            dataType: 'script',
            cache: true,
          
            success: function() {
              page.Tracker = _gat._getTracker('UA-2069074-8');
              page.Tracker._trackPageview();
            },   
            error: function() { throw "Unable to load ga.js; _gat has not been defined."; }
          });
        },

        show: function(idx) {
          if (page.tr.timer) clearTimeout(page.tr.timer);
          page.tr.showItem(idx);
        },
        
        facebookConnect: function() {   
          var loaded = null;
          var api_key = '7931eaa316e0274ce1e020e98253f117';
          var xd = '/media/xd_receiver.htm';
          $.ajax({
            url: 'http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/bs_BA',
            type: 'GET',
            dataType: 'script',
            cache: "cache",
            async: true,
            
            complete: function(){
              if (loaded == 1) {
                  var fb = $(document.createElement('fb:fan')).attr('profile_id', 137907587641).attr('stream', 0).attr('connections', 10).attr('width', 297);
                  $('div.front_news').append(fb);
              };
            },
          
            success: function() {
              FB.init(api_key, '/media/xd_receiver.htm');
              if ( FB.HiddenContainer.get() == null ) {
                var hc = $(document.createElement('div')).attr('id', 'FB_HiddenContainer').css('display', 'none').appendTo('body');
              }
              loaded = 1;
            },
          
            error: function() {
              throw "Unable to load FeatureLoader.";
            }
          });
        },
        
        lists: function(q) {
          var t = new Yetii({ id: q, interval: 20 });
        }
        
      };


      var jaaulde=window.jaaulde||{};jaaulde.utils=jaaulde.utils||{};jaaulde.utils.cookies=(function(){var resolveOptions,assembleOptionsString,parseCookies,constructor,defaultOptions={expiresAt:null,path:'/',domain:null,secure:false};resolveOptions=function(options){var returnValue,expireDate;if(typeof options!=='object'||options===null){returnValue=defaultOptions;}else
      {returnValue={expiresAt:defaultOptions.expiresAt,path:defaultOptions.path,domain:defaultOptions.domain,secure:defaultOptions.secure};if(typeof options.expiresAt==='object'&&options.expiresAt instanceof Date){returnValue.expiresAt=options.expiresAt;}else if(typeof options.hoursToLive==='number'&&options.hoursToLive!==0){expireDate=new Date();expireDate.setTime(expireDate.getTime()+(options.hoursToLive*60*60*1000));returnValue.expiresAt=expireDate;}if(typeof options.path==='string'&&options.path!==''){returnValue.path=options.path;}if(typeof options.domain==='string'&&options.domain!==''){returnValue.domain=options.domain;}if(options.secure===true){returnValue.secure=options.secure;}}return returnValue;};assembleOptionsString=function(options){options=resolveOptions(options);return((typeof options.expiresAt==='object'&&options.expiresAt instanceof Date?'; expires='+options.expiresAt.toGMTString():'')+'; path='+options.path+(typeof options.domain==='string'?'; domain='+options.domain:'')+(options.secure===true?'; secure':''));};parseCookies=function(){var cookies={},i,pair,name,value,separated=document.cookie.split(';'),unparsedValue;for(i=0;i<separated.length;i=i+1){pair=separated[i].split('=');name=pair[0].replace(/^\s*/,'').replace(/\s*$/,'');try
      {value=decodeURIComponent(pair[1]);}catch(e1){value=pair[1];}if(typeof JSON==='object'&&JSON!==null&&typeof JSON.parse==='function'){try
      {unparsedValue=value;value=JSON.parse(value);}catch(e2){value=unparsedValue;}}cookies[name]=value;}return cookies;};constructor=function(){};constructor.prototype.get=function(cookieName){var returnValue,item,cookies=parseCookies();if(typeof cookieName==='string'){returnValue=(typeof cookies[cookieName]!=='undefined')?cookies[cookieName]:null;}else if(typeof cookieName==='object'&&cookieName!==null){returnValue={};for(item in cookieName){if(typeof cookies[cookieName[item]]!=='undefined'){returnValue[cookieName[item]]=cookies[cookieName[item]];}else
      {returnValue[cookieName[item]]=null;}}}else
      {returnValue=cookies;}return returnValue;};constructor.prototype.filter=function(cookieNameRegExp){var cookieName,returnValue={},cookies=parseCookies();if(typeof cookieNameRegExp==='string'){cookieNameRegExp=new RegExp(cookieNameRegExp);}for(cookieName in cookies){if(cookieName.match(cookieNameRegExp)){returnValue[cookieName]=cookies[cookieName];}}return returnValue;};constructor.prototype.set=function(cookieName,value,options){if(typeof options!=='object'||options===null){options={};}if(typeof value==='undefined'||value===null){value='';options.hoursToLive=-8760;}else if(typeof value!=='string'){if(typeof JSON==='object'&&JSON!==null&&typeof JSON.stringify==='function'){value=JSON.stringify(value);}else
      {throw new Error('cookies.set() received non-string value and could not serialize.');}}var optionsString=assembleOptionsString(options);document.cookie=cookieName+'='+encodeURIComponent(value)+optionsString;};constructor.prototype.del=function(cookieName,options){var allCookies={},name;if(typeof options!=='object'||options===null){options={};}if(typeof cookieName==='boolean'&&cookieName===true){allCookies=this.get();}else if(typeof cookieName==='string'){allCookies[cookieName]=true;}for(name in allCookies){if(typeof name==='string'&&name!==''){this.set(name,null,options);}}};constructor.prototype.test=function(){var returnValue=false,testName='cT',testValue='data';this.set(testName,testValue);if(this.get(testName)===testValue){this.del(testName);returnValue=true;}return returnValue;};constructor.prototype.setOptions=function(options){if(typeof options!=='object'){options=null;}defaultOptions=resolveOptions(options);};return new constructor();})();(function(){if(window.jQuery){(function($){$.cookies=jaaulde.utils.cookies;var extensions={cookify:function(options){return this.each(function(){var i,nameAttrs=['name','id'],name,$this=$(this),value;for(i in nameAttrs){if(!isNaN(i)){name=$this.attr(nameAttrs[i]);if(typeof name==='string'&&name!==''){if($this.is(':checkbox, :radio')){if($this.attr('checked')){value=$this.val();}}else if($this.is(':input')){value=$this.val();}else
      {value=$this.html();}if(typeof value!=='string'||value===''){value=null;}$.cookies.set(name,value,options);break;}}}});},cookieFill:function(){return this.each(function(){var n,getN,nameAttrs=['name','id'],name,$this=$(this),value;getN=function(){n=nameAttrs.pop();return!!n;};while(getN()){name=$this.attr(n);if(typeof name==='string'&&name!==''){value=$.cookies.get(name);if(value!==null){if($this.is(':checkbox, :radio')){if($this.val()===value){$this.attr('checked','checked');}else
      {$this.removeAttr('checked');}}else if($this.is(':input')){$this.val(value);}else
      {$this.html(value);}}break;}}});},cookieBind:function(options){return this.each(function(){var $this=$(this);$this.cookieFill().change(function(){$this.cookify(options);});});}};$.each(extensions,function(i){$.fn[i]=this;});})(window.jQuery);}})();

head.ready(function() {

  $('a#look').live('click', function() {
    $location = $(this).attr('href');
    $.get($location, function(data) {
      $('#anketa_front').html(data);
    });
    
    return false;
  });
  
  $("a[data-confirm]").live("click", function(event){
    el = $(this);
    var delete_link = el.attr("href").split("/"); 
    var answer = confirm(el.attr("data-confirm"));
    if (answer) {
      $.post("/d/dc", {id: delete_link[1]}, function(data) {
        el.closest('p').fadeOut();
      });
    };
    event.preventDefault();
  });

  $('input[type="image"]').live('click', function(){
    var answer = $("input[name='answer']:radio:checked").val();
    $.ajax({
      url: 'vote',
      type: 'POST',
      data: {answer: answer},
      success: function(data) {
        $('#anketa_front').html(data);
      }
    });
    
    return false;
  });


  page.init();
});
