var $j = jQuery.noConflict();

$j(document).ready(function(){
  
  $j('#logo').click( function(){
    location.href = 'http://www.damonatuursteen.nl/';
  });

  $j('#logo').hoverPointer();
  
  if( $j('.slider').length > 0 ){
    $j('#content').buildSlider();
  };
  
  /** rebinding the send event */
  $j('.powermail_submit').click(function(event){
    event.preventDefault();
    //return false;
    
    /** check if input is valid */
    var tInputs = $j('.fieldsets input[required="required"]').length;
    var errMsg = [];
    
    $j('.fieldsets input[required="required"]').each(function(i){     
      if(!$j(this).checkValid()){
        //console.log('empty');
        errMsg.push($(this));
      }
      if(i == (tInputs-1) ){
        //console.log(errMsg.length);
        if(errMsg.length == 0){
          $j('.tx_powermail_pi1_form').submit();
        }
      }
    });
  }); 
  $j('input[placeholder], textarea[placeholder]').placeholder();

  if( $j('.menuSlideEffect').length > 0 ){
    $j('#left .bodytext').remove();
    var el = $j('.menuSlideEffect').eq(0);
    el.addClass('selected');
    $j('.bodytext', el).clone().appendTo('#left');
    
    $j('.menuSlideEffect').click( function(){
          $j('#left .bodytext').remove();
          $j('.menuSlideEffect').removeClass('selected');
          $j('.bodytext', $j(this)).clone().appendTo('#left');
          $j(this).addClass('selected');
    });
    
    /** 
      * Hover effect for cursor
      */
    $j('.menuSlideEffect').hoverPointer();
  };
  
  /**
   * Image block gallery
   */
  if( $j('.rightImgGallery img').length > 0 ){
    
    var workspace = $j('.rightImgGallery li');
    if(workspace.length == 0) {
      workspace = $j('.rightImgGallery .csc-textpic-imagecolumn');
      workspace.addClass('clip');
    } else {
      workspace.removeAttr('style');
      $j('.rightImgGallery .csc-textpic-imagecolumn, .rightImgGallery .csc-textpic-imagewrap, .rightImgGallery .csc-textpic-imagerow').removeAttr('style');
    
      //add large window
      var el = workspace.eq(0);
      
      //get filename
      var tSrc = $j('img', el).attr('src');
      var t = tSrc.split("/");
      tSrc = t[t.length -1];
      var title = tSrc.split(".jpg");
      
      $j('.rightImgGallery .csc-textpic').before('<div class="largeWindow">'+ el.html() +'<div class="title">'+title[0]+'</div></div>');
    
      //hover image effect
      workspace.hover(function (){
        $j(this).addClass('hover');
            if ($j('.rightImgGallery .largeWindow img').length > 0 ){
            $j('.rightImgGallery .largeWindow').empty(); 
            }
            //get filename
            var tSrc = $j('img', $j(this)).attr('src');
        var t = tSrc.split("/");
        tSrc = t[t.length -1];
        var title = tSrc.split(".jpg");
            
            $j('.rightImgGallery .largeWindow').append(  $j(this).html() +'<div class="title">'+title[0]+'</div>' );
      },function(){
        $j(this).removeClass('hover');
        });
      }
      
  }
  
  /**
   * Image overlay effect
   */
  if( $j('.overlayImage img').length > 0 ){
    $j('.overlayImage img').each(function(){
      $j(this).wrap('<a href="'+$j(this).attr('src')+'" rel="prettyPhoto[gallery]"></a>');
    });
    $j(".overlayImage a[rel^='prettyPhoto']").prettyPhoto({theme:'dark_square'});
    //$j('.overlayImage .csc-textpic-imagerow').eq(0).show();
    
    //preloader cover
    var imgBlank = new Image(); //"#images img:last"
    $j(imgBlank).load(function(){
      //var w = $j('.overlayImage img').width();
      //var h = $j('.overlayImage img').height();
      
      //if( w >= 265) {
      //   var r = 265/w;
      //   w = 265;
      //   h = Math.ceil(h * r);
      //} 
      //$j('.overlayImage').css({'height': h, 'width':w});
      //$j('.overlayImage img').eq(0).css({'height': h, 'width':w}).show();
      $j('.overlayImage img').eq(0).show();
      
    }).attr('src', $j('.overlayImage img:first').attr('src') );
  }
});

/** 
 * Function for displaying the caption with link on home page
 */
(function($) {
 $.fn.buildSlider = function(){
    //rebuild the caption for every slider conform layout
    $('.slider').each(function(){
  //save link
  var iHref = $('dt', this).attr('href');
  //replace img and remove link
  $('dt', this).append( $('img', this) );
  $('dt a', this).remove();
  //done
  
  //wrap caption with link and shadow
  var capHtml = $('dd', this).html();
  $('dd', this).html('');
  $('dd', this).append('<div class="caption"><a href="'+iHref+'">'+capHtml+' &gt;&gt;</a></div><div class="backdrop"></div>');
    });
    
    $(this).append('<div class="items"> </div>');
    $('#contentContainer').before('<a class="prev browse left"><a class="next browse right">');
    $(".items").append( $('.slider',this) );
    
    // initialize scrollable
    $("#content").scrollable();
 };
})(jQuery);

(function($) {
$.fn.hoverPointer = function(){
  this.each(function(){ 
    var c = this;
    
    $(this,c).hover(function(){
          $(this,c).addClass('hover');
      },function(){
        $(this,c).removeClass('hover');
      });
    });
};
})(jQuery);

(function($) {
$.fn.pager = function(pageItems){
  $(this).before('<ul id="tabItems"></ul>');
  
  var items = $('.projectItem', this).length;
  var pages = Math.ceil( 1*items/pageItems);
//  alert(items +'  pageItems:'+pageItems +'  pages:'+pages);
  var iter = 1;
  $('.projectItem', this).each(function(){
    desc = Math.ceil( 1*iter/pageItems);
    $(this).attr('description', desc);
    iter++;
  });
  var i=0;
  for (i=0;i<pages;i++){
    var z = i+1;
    $("ul#tabItems").append('<li><a href="#fragment-'+z+'"><span>'+z+'</span></a></li>');
    $(".projectItem[description='"+z+"']").wrapAll('<div id="fragment-'+z+'"></div>');
  };
  
  $('ul#tabItems').tabs();

};
})(jQuery);

Essentials = {
  compatOldBrowser : false ,
  siteURL: null,
  setCompatOldBrowser : function (){
    if ($j.browser.msie && $j.browser.version.substr(0,1)<7) {
        this.compatOldBrowser = true;
      }
    return null;
  },
  getCompatOldBrowser : function (){
    return this.compatOldBrowser;
  },  
  debugCompatOldBrowser : function(){
    alert( this.getCompatOldBrowser() );
  },
  getURLdetails: function(){
    this.siteURL = this.parseURL(document.location.href);
  },
  // This function creates a new anchor element and uses location
  // properties (inherent) to get the desired URL data. Some String
  // operations are used (to normalize results across browsers).
  parseURL: function (url) {
    var a =  document.createElement('a');
    a.href = url;
    return {
      source: url,
      protocol: a.protocol.replace(':',''),
      host: a.hostname,
      port: a.port,
      query: a.search,
      params: (function(){
      var ret = {},
      seg = a.search.replace(/^\?/,'').split('&'),
      len = seg.length, i = 0, s;
      for (;i<len;i++) {
        if (!seg[i]) { continue; }
          s = seg[i].split('=');
          ret[ unescape(s[0]) ] = s[1];
        }
        return ret;
      })(),
      file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
      hash: a.hash.replace('#',''),
      path: a.pathname.replace(/^([^\/])/,'/$1'),
      relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
      segments: a.pathname.replace(/^\//,'').split('/')
    };
  }
};


(function($){
 $.fn.checkValid = function(){
  var inpt = $(this);  
  var parentInpt = $(this).parent();
  
  if(inpt.val() == ''){
    if(!inpt.hasClass('err')) {
      inpt.addClass('err');
      inpt.after('<span class="errMsg">dit is een verplicht veld</span>');
    }
    if( $('.err', parentInpt).length == 0)
      parentInpt.addClass('err');
    
    return false;
  } else {
    inpt.removeClass('err');
    parentInpt.find('.errMSg').remove();
    
    parentInpt.removeClass('err');
    return true;
  }
 }  
}) (jQuery);

/*
* Placeholder plugin for jQuery
* ---
* Copyright 2010, Daniel Stocks (http://webcloud.se)
* Released under the MIT, BSD, and GPL Licenses.
*/
(function($) {
    function Placeholder(input) {
        this.input = input;
        if (input.attr('type') == 'password') {
            this.handlePassword();
        }
        // Prevent placeholder values from submitting

        $(input[0].form).submit(function() {
            if (input.hasClass('placeholder') && input[0].value == input.attr('placeholder')) {
                input[0].value = '';
            }
        });
    }
    Placeholder.prototype = {
        show : function(loading) {
            // FF and IE saves values when you refresh the page. If the user refreshes the page with
            // the placeholders showing they will be the default values and the input fields won't be empty.
            if (this.input[0].value === '' || (loading && this.valueIsPlaceholder())) {
                if (this.isPassword) {
                    try {
                        this.input[0].setAttribute('type', 'text');
                    } catch (e) {
                        this.input.before(this.fakePassword.show()).hide();
                    }
                }
                this.input.addClass('placeholder');
                this.input[0].value = this.input.attr('placeholder');
            }
        },
        hide : function() {
            if (this.valueIsPlaceholder() && this.input.hasClass('placeholder')) {
                this.input.removeClass('placeholder');
                this.input[0].value = '';
                if (this.isPassword) {
                    try {
                        this.input[0].setAttribute('type', 'password');
                    } catch (e) { }
                    // Restore focus for Opera and IE
                    this.input.show();
                    this.input[0].focus();
                }
            }
        },
        valueIsPlaceholder : function() {
            return this.input[0].value == this.input.attr('placeholder');
        },
        handlePassword: function() {
            var input = this.input;
            input.attr('realType', 'password');
            this.isPassword = true;
            // IE < 9 doesn't allow changing the type of password inputs
            if ($.browser.msie && input[0].outerHTML) {
                var fakeHTML = $(input[0].outerHTML.replace(/type=(['"])?password\1/gi, 'type=$1text$1'));
                this.fakePassword = fakeHTML.val(input.attr('placeholder')).addClass('placeholder').focus(function() {
                    input.trigger('focus');
                    $(this).hide();
                });
                $(input[0].form).submit(function() {
                    fakeHTML.remove();
                    input.show()
                });
            }
        }
    };
    var NATIVE_SUPPORT = !!("placeholder" in document.createElement( "input" ));
    $.fn.placeholder = function() {
        return NATIVE_SUPPORT ? this : this.each(function() {
            var input = $(this);
            var placeholder = new Placeholder(input);
            placeholder.show(true);
            input.focus(function() {
                placeholder.hide();
            });
            input.blur(function() {
                placeholder.show(false);
            });

            // On page refresh, IE doesn't re-populate user input
            // until the window.onload event is fired.
            if ($.browser.msie) {
                $(window).load(function() {
                    if(input.val()) {
                        input.removeClass("placeholder");
                    }
                    placeholder.show(true);
                });
                // What's even worse, the text cursor disappears
                // when tabbing between text inputs, here's a fix
                input.focus(function() {
                    if(this.value == "") {
                        var range = this.createTextRange();
                        range.collapse(true);
                        range.moveStart('character', 0);
                        range.select();
                    }
                });
            }
        });
    }
})(jQuery);
