/*
 * JavaScript Functions for iZ-smart.net
 * http://www.iZ-smart.net
 *
 * Copyright 2011, Christian Boenning <hexa@iZ-smart.net>
 *
*/

$(function () {
  // Mitchatten Badge verstecken sofern wir fuer ein Mobile Device rendern
  if ($(this).has('#mitchatten')) {
    $.getJSON('http://wwwapi.iz-smart.net/2/info/?jsoncallback=?', {
      'cache': 'md' + Math.random()
    }, function (data) {
      if (data.izsmart.mobile === true) {
        $('#mitchatten').hide();
      }
    });
  }

  // Fancybox 
  $.fn.getTitle = function () {
    var arr = $("a.fancybox");
    $.each(arr, function () {
      var title = $(this).children("img").attr("title");
      $(this).attr('title', title);
    });
  };

  var thumbnails = 'a:has(img)[href$=".gif"],a:has(img)[href$=".jpg"],a:has(img)[href$=".jpeg"],a:has(img)[href$=".png"]', 
    FancyContainers = "#mail2opers,#mail2helpdesk,#feedback,#flood,#flood2";
  
  $("a[href*='.jpg']").addClass("fancybox").attr("rel", "fancybox");
  $("a[href*='.png']").addClass("fancybox").attr("rel", "fancybox");
  $(thumbnails).addClass("fancybox").attr("rel", "fancybox").getTitle();
  $("a.fancybox").fancybox({
    'padding': 10,
    'margin': 20,
    'width': 950,
    'height': 640,
    'autoScale': true,
    'autoDimensions': false,
    'centerOnScroll': true,
    'transitionIn': 'elastic',
    'transitionOut': 'elastic',
    'speedIn': 500,
    'speedOut': 500,
    'changeSpeed': 300,
    'showNavArrows': false,
    'easingIn': "easeOutBack",
    'easingOut': "easeInBack",
    'easingChange': "easeInOutQuart"
  });

  // IFrames-Fancybox
  $(FancyContainers).fancybox({
    'width': '75%',
    'height': '90%',
    'autoScale': false,
    'easingIn': "easeOutBack",
    'easingOut': "easeInBack",
    'easingChange': "easeInOutQuart",
    'type': 'iframe'
  });

  // mark thumbs for linking
  $("a > img").addClass("thumb");

  // tipsy
  $('a[title]').tipsy({
    delayIn: 250,
    delayOut: 500,
    fade: true,
    fallback: '',
    gravity: $.fn.tipsy.autoWE,
    html: false,
    opacity: 0.8,
    title: 'title',
    maxWidth: 350
  });

  // site version (title of copyright)
  $('#version').tipsy({
    gravity: 'ne',
    fade: true,
    delayIn: 250,
    delayOut: 500,
    maxWidth: 350
  });
  
  $('.section .contents').hide();
  $('.section h4').click(function () {
    var hidden = $(this).next().is(':hidden');
    $(this).next().slideToggle('slow');
    return hidden;
  });
});

function filterData(data) {
  data = data.replace(/<?\/body[^>]*>/g, '');
  data = data.replace(/[\r|\n]+/g, '');
  data = data.replace(/<--[\S\s]*?-->/g, '');
  data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
  data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
  data = data.replace(/<script.*\/>/, '');
  return data;
}

function doCrossDomainAjaxRequest(url, target) {
  $.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22 ' + encodeURIComponent(url) + '%22&format=xml&callback=?', function (data) {
    if (data.results[0]) {
      data = filterData(data.results[0]);
      $(target).html(data);
    } else {
      var errormsg = '<p>Error: could not load the page.</p>';
      $(target).html(errormsg);
    }
  });
}

function strpos (haystack, needle, offset) {
  // original source at http://phpjs.org/
  var i = (haystack + '').indexOf(needle, (offset || 0));
  return i === -1 ? false : i;
}

function uniqid (prefix, more_entropy) {
  // original source at http://phpjs.org/

  if (typeof prefix == 'undefined') {
    prefix = "";
  }

  var retId;
  var formatSeed = function (seed, reqWidth) {
    seed = parseInt(seed, 10).toString(16); // to hex str
    if (reqWidth < seed.length) { // so long we split
      return seed.slice(seed.length - reqWidth);
    }
    if (reqWidth > seed.length) { // so short we pad
      return Array(1 + (reqWidth - seed.length)).join('0') + seed;
    }
    return seed;
  };

  // BEGIN REDUNDANT
  if (!this.php_js) {
    this.php_js = {};
  }
  // END REDUNDANT
  if (!this.php_js.uniqidSeed) { // init seed with big random int
      this.php_js.uniqidSeed = Math.floor(Math.random() * 0x75bcd15);
  }
  this.php_js.uniqidSeed++;

  retId = prefix; // start with prefix, add current milliseconds hex string
  retId += formatSeed(parseInt(new Date().getTime() / 1000, 10), 8);
  retId += formatSeed(this.php_js.uniqidSeed, 5); // add seed hex string
  if (more_entropy) {
    // for more entropy we add a float lower to 10
    retId += (Math.random() * 10).toFixed(8).toString();
  }

  return retId;
}

function openWebchat() {
  window.open('http://www.iZ-smart.net/webchat.html', 'Webchat', 'width=1100,height=700,scrollbars=no');
}

function shareFacebook() {
  window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(location.href) + '&t=' + encodeURIComponent(document.title), 'sharer', 'toolbar=0,status=0,width=626,height=436');
}

function shareTwitter() {
  window.open('http://twitter.com/home?status=Lese gerade bei @izsmart: ' + encodeURIComponent(location.href), 'Twitter', 'toolbar=0,status=0,width=800,height=600,scrollbars=yes');
}

// Debug, Debug, Debug
if (typeof console == "undefined") {
  console = {
    log: function() { },
    error: function() { },
    info: function() { },
    debug: function() { },
    warn: function() { },
    trace: function() { },
    dir: function() { },
    dirxml: function() { },
    group: function() { },
    groupEnd: function() { },
    time: function() { },
    timeEnd: function() { },
    assert: function() { },
    profile: function() { }
  }
}

window.onerror = function (desc, page, line, chr) {
  if (this.console) {
    console.log('JavaScript Error - Desc: ' + desc + ' - Page: ' + page + ' - Line: ' + line);
  }
};
