//window.onbeforeunload = function(){ return 'leave this page?';};

$(function(){
	
	// highlights links
	var ll = document.links, loc=document.location.href ? document.location.href : document.location, self = /\/([^\/]*)(\?.+)?$/g.exec(loc)[0];	
	for(i in ll){ if(loc.indexOf(ll[i].href) != -1 || self.indexOf(ll[i].rel)>0) ll[i].className += ' active'; }
	
	$('table[border=0], img:not([border]),img[border=0]').addClass('no-border');
	
	$('a[rel*=external]').attr('target','_blank');
	
	if($("a[rel^=lightbox]").size()){
		// fancybox initialization
		$("a[rel^=lightbox]").fancybox({
		   	"titlePosition"		: 'inside',
		   	"overlayOpacity"	: 0.8,
			"overlayColor"		: '#000000',
			'transitionIn'		: 'elastic',		
			'titleFormat'       : function(title, currentArray, currentIndex, currentOpts){
				var text = '';
				if(currentArray.length > 1) text = '<strong>' + title + '</strong>' + 'Image ' +  (currentIndex + 1) + ' of ' + currentArray.length;
			/*	if($(currentArray[currentIndex]).attr('data-orig')){
					var rev = $(currentArray[currentIndex]).attr('data-orig').split('|');
					text += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/getfile.php?qf='+rev[0]+'">Download original version</a> ('+rev[1]+')';
				} */
				return '<span id="fancybox-title-inside">'+ text + '</span>';
			}
		});
	}
	
	$("#add_wishlist_frm").submit(function(){
		var $frm = $(this);
		if($('[name=wishlist_title]').val()==''){
			alert('Wishlist title is required!');
			return false;
		}
	});
	
	
	$('.messages').hide().fadeIn(1500);
	
	$(":input[title], textarea[title]").hint();
	
	//init tabs
 	$('.tabs').each(function(){
 		var $tabs = $(this),
 			$tabsList = $('>a[href^=#], >li>a[href^=#]',$tabs),
		 	contentsSelectors = [];
		 	$($tabsList).each(function(){
		 		contentsSelectors[contentsSelectors.length] = $(this).attr('href');
				 if(!$(this).hasClass('active')){ // hide inactive tabs
				 	$( $(this).attr('href') ).hide();
				 }
		 	});
		 	
			$($tabsList).click(function(){
	 				$(contentsSelectors.join(',')).hide();
				 	$tabsList.removeClass('active');
					var contentActiveSelector = $(this).blur().addClass('active').attr('href'), $contentActive = $(contentActiveSelector);
					$contentActive.show();
					location.hash = 'tab='+contentActiveSelector.replace('#','');
					return !1;
				 });
		 	if(location.hash.indexOf('#tab=')===0){$('a[href^=#' +location.hash.replace('#tab=','')+']').click(); }
 	});
	
	
});


$.fn.addLoader = function(){
	var css = 'position:absolute;z-index:9999;top:0;left:0;height:'+($(this).outerHeight())+'px;width:'+$(this).outerWidth()+'px';
	$('<div class="loader-splash" style="'+css+'"></div>').appendTo($(this));
	$(this).addClass('loader').css('position','relative');
}

$.fn.removeLoader = function(){
	$(this).removeClass('loader').css('position','').find('.loader-splash').remove();
}

// no spam js, for the future
/*
$(function() {
      $('span.no-spam').each(
        function() {
          var address = $(this).text();
          address = address.replace(' at-no-spam ', '@');
          address = address.replace(' dot-no-spam ', '.');
          var link = $('<a href="mailto:'+ address +'">'+ address +'</a>');
          $(this).empty().append(link);
        }
      );
});
*/

/*** plugins ***/
/**
* @author Remy Sharp
* @url http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
*/
$.fn.hint = function (blurClass) {
  if (!blurClass) { 
    blurClass = 'blur';
  }
 
  return this.each(function () {
    // get jQuery version of 'this'
    var $input = $(this),
    
    // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = $(this.form),
      $win = $(window);

    function remove() {
      if ($input.val() === title && $input.hasClass(blurClass)) {
        $input.val('').removeClass(blurClass);
      }
    }

    // only apply logic if the element has the attribute
    if (title) { 
      // on blur, set value to title attr if text is blank
      $input.blur(function () {
        if (this.value === '') {
          $input.val(title).addClass(blurClass);
        }
      }).focus(remove).blur(); // now change all inputs to title
      
      // clear the pre-defined text when form is submitted
      $form.submit(remove);
      $win.unload(remove); // handles Firefox's autocomplete
    }
  });
};

/*** funcs ****/
function popup(src, width, height, title, add_html){
	var html = '<html><head><title>' + title + '</title><link rel="stylesheet" type="text/css" href="/styles/popup.css" /></head><body style="margin:0;padding:0;"><img src="' + src + '" width="' + width + '" height="' + height + '" alt="" style="display:block;cursor:pointer;" onclick="window.close()" /><div id="caption"><p>' + title + (add_html ? ' ' + add_html : '') + '</p></div></body></html>';
	var x = (screen.width - width) / 2;
	var y = (screen.height - height) / 2;
	var wnd = window.open('', '', 'toolbar=0,location=1,directories=0,menuBar=0,scrollbars=0,resizable=1,width=' + width + ',height=' + height + ',left=' + x + ',top=' + y + ',screenX=' + x + ',screenY=' + y);
	wnd.document.open();
	wnd.document.write(html);
	wnd.document.close();
}

function bm_add(t, url, title){
	var goto;
	switch(t){
		case 'favourites':
			if(window.sidebar)
				window.sidebar.addPanel(title, url, "");
			else if(window.opera && window.print){
				var elem = document.createElement('a');
				elem.setAttribute('href', url);
				elem.setAttribute('title', title);
				elem.setAttribute('rel', 'sidebar');
				elem.click();
			} 
			else if(document.all)
				window.external.AddFavorite(url, title);
			return;
		break;
		case 'google':
			goto = 'http://www.google.com/bookmarks/mark?op=add&bkmk=' + url + '&title=' + title;
		break;
		case 'yahoo':
			goto = 'http://myweb2.search.yahoo.com/myresults/bookmarklet?u=' + url + '&t=' + title + '&d=&ei=UTF-8';
		break;
		case 'facebook':
			goto = 'http://www.facebook.com/sharer.php?u=' + url + '&t=' + title;
		break;
		case 'myspace':
			goto = 'http://www.myspace.com/Modules/PostTo/Pages/?u=' + url + '&t=' + title + '&c=';
		break;
		case 'twitter':
			goto = 'http://twitter.com/home?status=' + url + ' via @addthis';
		break;
		case 'live':
			goto = 'https://favorites.live.com/quickadd.aspx?marklet=1&mkt=en-us&url=' + url + '&title=' + title + '&top=1';
		break;
		case 'linkedin':
			goto = 'http://www.linkedin.com/shareArticle?mini=true&url=' + url + '&title=' + title + '&ro=false&summary=&source=';
		break;
	}
	window.open(goto);
}

function format_price(str){
	var pr = parseFloat(str);
	var p1 = Math.floor(pr);
	var p2 = pr - p1;
	var p2_str;
	if(p2 == 0)
		p2_str = '00';
	else{
		p2 = Math.floor(p2 * 100);
		p2_str = (p2 < 10 ? '0' : '') + p2;
	}

	var p1_r = [], j = 0;
	for(i = p1.length - 1; i >= 0; i--){
		j++;
		p1_r.unshift(p1.charAt(i));
		if(j % 3 == 0 && i != 0)
			p1_r.unshift(',');
	}
	return p1_r.join('') + '.' + p2_str;
}

function loadImages(imagesList, index){
	index=index||0;
	var max = imagesList.length-1;
	$(imagesList[index]).load(function(){
		$(this).show();
		index++;
		if(index<=max) loadImages(imagesList, index);
		else onFinish;
	}).error(function(){
		index++;
		if(index<=max) loadImages(imagesList, index);
		else onFinish;
	});
}

