/* Any JavaScript here will be loaded for all users on every page load. */


/*
 *
 *   S E T T I N G S
 *
 */

var expandUrl = '/Oglas';
var cartUrl = '/Izbrani oglasi';
var compareUrl = '/Primerjaj';
var compareWithUrl = '/Primerjaj z';
var editImagesUrl = '/Uredi_slike';
var uploadUrl = '/wiki/index.php?title=Special:Upload';
var searchUrl = '/Iskanje';
var searchModelUrl = '/Modeli za iskanje';
var editFormModelUrl = '/Modeli za urejanje';
var blackScreenThrobber = "/images/7/76/Ajax-throbber.gif"
var sliderDelay = 5000;
var slider_interval;
var block_sliding = true;

/*
 *
 *   H E L P E R S
 *
 */
/*

//documentWriteTarget=$('body');
function setWriteTarget(el)
{
  documentWriteTarget=el;
}
document.write = function(str){
	trg=documentWriteTarget.find('*:last').parent();
//	trg=els.eq(els.length-1).parent();
	ins = $('<div>'+str+'</div>');
	ins.children().each(function()
	{
		trg.append(this);
	});
};
*/


function extractValues(form)
{
  ret = {};
  $(form).find(':input').each (function (n) {
    t=$(this);
    ret[t.attr('name')]=t.val();
  });
  return ret;
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */



jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

jQuery.fn.extend({
	loadBefore: function (url, params, cb)
	{	
   		el=this;
  		$.get(url, params , function (data, error)
   		{
      		if (cb && !cb(data,error)) return;
      		el.before($(data));
   		});
	},
	loadAfter: function (url, params, cb)
	{	
   		el=this;
  		$.get(url, params , function (data, error)
   		{
      		if (cb && !cb(data,error)) return;
      		el.before($(data));
   		});
	}
});

$.fn.insertAtCaret = function (myValue) {
        return this.each(function(){
                //IE support
                if (document.selection) {
                        this.focus();
                        sel = document.selection.createRange();
                        sel.text = myValue;
                        this.focus();
                }
                //MOZILLA/NETSCAPE support
                else if (this.selectionStart || this.selectionStart == '0') {
                        var startPos = this.selectionStart;
                        var endPos = this.selectionEnd;
                        var scrollTop = this.scrollTop;
                        this.value = this.value.substring(0, startPos)
                                      + myValue
                              		  + this.value.substring(endPos, this.value.length);
                        this.focus();
                        this.selectionStart = startPos + myValue.length;
                        this.selectionEnd = startPos + myValue.length;
                        this.scrollTop = scrollTop;
                } else {
                        this.value += myValue;
                        this.focus();
                }
        });
};

$(document).ready( function() {
	$('#wpTextbox1').keydown( function (e) { if (e.which ==9) {e.preventDefault(); }} );
	$('#wpTextbox1').keyup( function (e) { if (e.which ==9) {e.preventDefault(); }} );
	$('#wpTextbox1').keypress( function (e) { if (e.keyCode ==9) {e.preventDefault(); $(this).insertAtCaret('\t'); } } );
});
/*
 *
 *  S E T U P   P A G E
 *
 */ 

var SliderObj = function () {
	//   return true;
	me = this;

	me.frame = $('#adslider-wrap');

	slider = me.slider = me.frame.find('.adslider');

	me.block_sliding = wgUserName ? true : false;

	me.position=0;
	
	me.resize = function () 
	{
		me.itemwidth = slider.children('.flipcard:first').width();
		me.step = Math.round(me.frame.width() / me.itemwidth);
		slider.css('width',slider.children('.flipcard').length*me.itemwidth);
	};
		   
	me.onload = function() 
	{
		me.count = slider.children('.flipcard').length;
		counter = 0;
		while (counter < 10 || me.count + counter < 20 )
		{
			slider.children('.flipcard').eq(counter).clone().appendTo(slider);
			counter++;
		} 
		me.limit = me.count+counter;
		//set slider width!
		
		me.resize();
		me.position = 0;
		//   top.alert(limit);
	};

	   slider.mouseover(function(e){
		  me.block_sliding = true;
	   });
	   slider.mouseout(function(e){
		  me.block_sliding = false;
	   });

	   me.frame.find('.icon-prev').click(function(e){
	   	  me.block_sliding = true;
	   	  me.back(500);
	   });
	   me.frame.find('.icon-prev').mouseout(function(e){
	   	  slider.stop();
	   	  me.block_sliding = false;
	   });
	   me.frame.find('.icon-next').click(function(e){
	   	  me.block_sliding = true;
	   	  me.forward(500);
	   });
	   me.frame.find('.icon-next').mouseout(function(e){
	   	  slider.stop();
	   	  me.block_sliding = false;
	   });
	  
	   me.forward = function (time) {
	   	 time=time||1500;
		 if (me.position+2*me.step >= me.limit ) {
		 	me.position = me.position - me.count;
		    slider.css('left', -me.position*me.itemwidth);
		 }
		 me.position = me.position + me.step;
	//     slider.css('left',-position);
		   slider.animate({ 
		    left: -me.position*me.itemwidth
		 }, time, 'swing' );
	   };

	   me.back = function (time) {
	   	 time=time||1500;
		 if (me.position-me.step <= 0 ) {
		 	me.position = me.position + me.count;
		    slider.css('left', -me.position*me.itemwidth);
		 }
		 me.position = me.position - me.step;
	//     slider.css('left',-position);
		   slider.animate({ 
		    left: -me.position*me.itemwidth
		 }, time, 'swing' );
	   };
		
		me.doSlide = function()
		{
		  if (me.block_sliding) return;
		  me.forward(750);
		}
		
	   slider_interval = setInterval(me.doSlide,sliderDelay);
};

// called once
function setupPage()
{

//  setupSlider();
  setupResize();
  setupSearch();
  
  $('input:text').focus(function(){ if ($(this).val()=='0') $(this).val('');});
  $('.field-submit').hover(
  	function(e) {$(this).addClass('hover')},
  	function(e) {$(this).removeClass('hover')}
  );
	$(document).dblclick( function (e)
	{
	   if (e.pageX<20 && e.pageY<20) top.location.href='/Special:UserLogin'; 
	});
	$('#wpTextbox1').dblclick(function(e)
	{
		if (e.ctrlKey)
		{
			me=$(this);
			if (me.attr('style')) me.attr('style','');
			else me.css({
				'position':'fixed',
				'top':0,
				'left':0,
				'width':'100%',
				'height':'100%',
				zIndex:5000
			});
		}
	});
	setupStuff();
}



// called once per ajax call
function setupStuff()
{
	if (!$) return;
	setupTooltips();
	$('.form #control-Brand').change( function (e)
	{
		$.get ( editFormModelUrl, 
		{
			'action':'render', 
			'Brand':$('#control-Brand').val() 
		}, 
		function (data) 
		{      
			$('#field-control-Model').replaceWith(data);
			setupTooltips();
		});
	});
	setupUpload();
}


function setupResize() {
var em = 12;
var busy = false;
var fn = function (e) {
       if (busy) return;
       busy = true;
       var wd = Math.max(Math.floor(($(window).width()-20)/16/em)*16*em,32*em);
       if (wd<64*em) {
	     $('#header-wrap').width(wd);
         $('#adslider-wrap').css('clear','left');
         $('#content').width(wd);
       } else {
	     $('#header-wrap').width(wd);
         $('#adslider-wrap').css('clear','none');
         $('#content').width(wd);
       }
       Slider.resize();
       var ht = $(window).height();
       var cssTop = $('#clear').offset().top;
       if (ht-cssTop<30*em) {
         $('#content-wrap').css('height','auto');
         $('#canvas').css('overflow-y','scroll');
       } else {
		 $('#canvas').scrollTop(0);
         $('#content-wrap').css('height',$('#canvas').height() - cssTop);
         $('#canvas').css('overflow-y','hidden');
       }
       busy = false;
   };
   fn();
   $(window).resize(fn);
}

function setupRoundedCorners () {
return true;
    var xbox = RUZEE.ShadedBorder.create({ corner:6, edges:"tblr", border:1, drawOuter:false});
    //xbox.render($(".flipcard .inner"));
    var cardbox = RUZEE.ShadedBorder.create({ corner:9, edges:"tblr", border:1, drawOuter:false});
    //cardbox.render($(".card .inner"));
    //cardbox.render($(".brandcard .inner"));
    //cardbox.render($(".dealercard .inner"));
}


function setupSearch ()
{
/*
	$('.search-form FORM').submit( function(e)
	{
        params = extractValues(this);
        loadSearch(params);
	    e.stopPropagation();
        e.preventDefault();
	    return false;
	});
*/
		fn = function (e)
        {
           $.get(searchModelUrl, {action:'render','search-brand':$('#control-search-brand').val()}, function (data) { $('#field-control-search-model').replaceWith($(data).find('.field-select')); setupTooltips();});
        };
        $('#control-search-brand').change(fn);
        fn();
}



/*
 *
 *   T O O L T I P S 
 *
 */

function hideTooltip()
{
    $('#tooltip-wrap').remove();
}

function showTooltip(anchor,tip) /* preferred coordinates, min size */
{
    hideTooltip();
    em = 12;
    W = $(window);
    D = $("body");
    D.append('<div id="tooltip-wrap" style="z-index:3400"><div id="tooltip" style="float:right;"><div id="tooltip-inner" style="float:right">'+tip+'</div></div></div>');
    TW = $('#tooltip-wrap');
    T = $('#tooltip');
    TI = $('#tooltip-inner');
    screenWidth = W.width();
    screenHeight = W.height();
    
    targetWidth = TI.width();
    targetHeight = TI.height();
    marginTop = 1*em;
    margin = em / 2;
    
    if (anchor.width()<24) targetRight = anchor.offset().left + anchor.width()/2 + 12;
    else targetRight = anchor.offset().left+anchor.width(); 
    targetBottom = anchor.offset().top -margin;     
    T.css({display:'none'});
    TW.css({position:'absolute',right:screenWidth-targetRight,bottom:screenHeight-targetBottom,width:targetWidth+12});
    T.fadeIn('fast');
}

function setupTooltips() // ne rabi pazit na klaso .setup, ker odstrani title atribute
{
  $('span[title],div[title]').each( function (n)
  {
    t = $(this);
    t.attr( 'tooltip',t.attr('title'));
  });

  $('span[title],div[title]').hover(
     function (e) {  t =$(this); showTooltip(t,t.attr('tooltip')) },
     function (e) { hideTooltip()}
  );
 
  $('span[title],div[title]').attr('title','');
}

/*
 *
 *   A J A X  H A N D L E R S
 *
 */

function loadFromLink(link,params,callback)
{
   params = params || {};
   params.action='render';
   $('#content').load( $(link).attr('href') , params , callback);
}

function loadSearch(params, callback)
{
  params.action = 'render';
  $.post(searchUrl, params, function (data, error)
  {
    //$('#content').html('');
	ins = $('<div>'+data+'</div>');
	$('#content').html('');
	ins.children().appendTo($('#content'));
	//$('#content').append(ins);
	setupStuff();
	callback && callback()
  });
}

function copyContents(srcNode, trgNode)
{
	src =$(srcNode); trg=$(trgNode);
	if (src.children().length==0)
	{
		trg.append(src);
	}
	else src.children().each( function (n)
	{
		copy = $(this).clone();
		copy.empty();
		trg.append(copy);
		copyContents(this,copy);
	});
}

function loadLinkAfter(link,el)
{
	$(el).eq(0).loadAfter($(link).attr('href'),{action:'render'})
}

function loadLinkBefore(link,el)
{
	$(el).eq(0).loadBefore($(link).attr('href'),{action:'render'})
}

function reloadCart(params,callback)
{
   params.action = 'render';

   $.get(cartUrl, params, function (data, error)
   {
      $('.cart').remove();
      $('#cart-before').after($(data));
      setupStuff();
      callback && callback();
   });
}

function loadLink(link, targetSelector, callback)
{
	// jquerize the link
	link = $(link);
	
	// if we don't have a target, use #content, if that fails, use document
	target = targetSelector ? link.parents(targetSelector) : $('#content');
	target = target.length ? target : $(targetSelector);
	target = target.length ? target : $('#content');
	target = target.length ? target : $("body");

	// load new content
	$.get( link.attr('href'), { action : 'render', dummy : Math.random() } , function(data,error) {
	    try
	    {
	      target.html(data);
	      setupStuff();
		} catch(e) {alert (target.attr('id'))}
		typeof(callback)=='function' && callback();
		return false;
	},'html');
}

function loadContent(link, anchorSelector, callback)
{
	try
	{
		link = $(link);
		if(link.blur) link.blur();
		anchor = anchorSelector ? link.parents(anchorSelector) : link;
		anchor = anchor.length ? anchor : link;
		// show black screen with throbber at the anchor
		showBlackScreen(anchor.offset().left,anchor.offset().top);
	
		// load new content
		loadLink( link, '#content', function() {
			// hide black screen when done
			hideBlackScreen()
		});
	}
	catch (e) { hideBlackScreen(); }
}

function showBlackScreen(anchorX,anchorY)
{
	var D = $("body");
	var B = $('#blackscreen');
	if (anchorY!=null) zOffset = 10; else zOffset = 0;
	if (B.length)
	{
		B.css({zIndex:3000 + modalStackTop * 10 - 5 + zOffset});
		B.show();
	}
	else
	{
		D.append('<div id="blackscreen"><div id="blackscreen-throbber" style="display:none"></div></div>');
		B = $('#blackscreen');
		B.bgiframe();
		B.css({
			position: 'absolute',
			left: 0, width: '100%',
			top: 0, height: '100%',
			background: 'url(images/nav/modalbackground.png)',
			opacity: .5,
			zIndex : 3000 + modalStackTop * 10 - 5 + zOffset
		});
	}
	
	BT = $('#blackscreen-throbber');
	
    if (anchorY==null)
    {
    	$('#blackscreen-throbber').hide();
    }
    else
    {
	
		tLeft = anchorX - BT.width()/2;

		tTop = anchorY - BT.height()/2;
		
		BT.css({
			'left':tLeft,
			'top':tTop 
		});
		BT.show();
	}
	return B;
}

function hideBlackScreen()
{
	if (modalStackTop>0)
	{
		$('#blackscreen').css({zIndex:3000 + modalStackTop * 10 - 5});
	}
	else
	{
		$('#blackscreen').hide();
	}
}

function hideSplash(callback)
{
    hideTooltip();
    $('#splash').fadeOut('fast',function(n) { $('#splash-wrap').remove(); $(this).remove(); });
}

function postToModal(form,anchorSelector,minWidth, minHeight)
{
	params = extractValues(form);
	params.action='render';
	try
	{
		form = $(form);
		if(form.blur) form.blur();
		anchor = anchorSelector ? form.parents(anchorSelector) : form;
		anchor = anchor.length ? anchor : form;
		anchorX = anchor.offset().left + anchor.width()/2;
		anchorY = anchor.offset().top + anchor.height()/2;
		// show black screen with throbber at the anchor
		showBlackScreen(anchorX,anchorY);
	
		// load new content
		$.post( form.attr('action'), params, function(data) {
			showModal(data,anchorX,anchorY,minWidth,minHeight);
			showBlackScreen();
		});
	}
	catch (e) { }
}

function loadModal(link, anchorSelector, minWidth, minHeight)
{
	try
	{
		link = $(link);
		if(link.blur) link.blur();
		anchor = anchorSelector ? link.parents(anchorSelector) : link;
		anchor = anchor.length ? anchor : link;
		anchorX = anchor.offset().left + anchor.width()/2;
		anchorY = anchor.offset().top + anchor.height()/2;
		// show black screen with throbber at the anchor
		showBlackScreen(anchorX,anchorY);
	
		// load new content
		$.get( link.attr('href'), {action:'render'}, function(data) {
			showModal(data,anchorX,anchorY,minWidth,minHeight);
			setupStuff();
			showBlackScreen();
		});
	}
	catch (e) { }
}

var modalStackTop = 0;

function showModal(content, anchorX, anchorY, minWidth, minHeight) /* preferred coordinates, min size */
{
	modalStackTop++;
	minWidth = minWidth || 40;
	minHeight = minHeight || 30;
	
	modalId = 'modal-' + modalStackTop;
	modalWrapId = 'modal-wrap-' + modalStackTop;
	
    hideTooltip(); //TODO: move to unsetStuff() or similar
	//hideModal(true);	
    em = 12;
    margin = 0; 
    minWidth = minWidth * em;
    minHeight = minHeight * em;


    W = $(window);
    D = $("body");

    screenWidth = D.width()-2*em;
    screenHeight = D.height()-2*em;

	D.append('<div id="' + modalWrapId + '" style="position:absolute" >'
			+'<div id="' + modalId + '" style="position:relative;float:left;">'
			+'</div></div>');

	M = $('#'+modalId);
	M.hide();
	MW = $('#'+modalWrapId);
	
	MW.css({
		background:'transparent', 
		position:'absolute',
		display:'block', 
		top:0, 
		left:0, 
		width:'100%', 
		height:'100%', 
		overflow:'auto',
		zIndex : 3000 + modalStackTop * 10 - 5
	});

	MW.click(function(e) {
		if (e.target==this)	hideModal();
	})
	
	if (screenWidth>screenHeight)
	{
		M.addClass('modal-landscape')
	}
	else
	{
		M.addClass('modal-portrait')
	}	
	// put the new content into modal
	M.html(content);

	// find the desired dimensions
    targetWidth = M.width();
    targetHeight = M.height();
	
	//try to shuffle the content
	if (targetWidth>screenWidth-2*margin)
	{
		M.addClass('modal-narrow');
		targetWidth = M.width();
		targetHeight = M.height();
	}
	
	if (targetHeight>screenHeight-2*margin)
	{
		M.addClass('modal-short');
		targetWidth = M.width();
		targetHeight = M.height();
	}	
	
	/* console.log(targetWidth+'|'+targetHeight); */
	
	// impose minimum dimensions
	if (minWidth && targetWidth < minWidth) targetWidth=minWidth;
	if (minHeight && targetHeight < minHeight) targetHeight=minHeight;
 	
 	// find the desired position
    targetLeft = (screenWidth - targetWidth) / 2;
    targetTop = (screenHeight - targetHeight) / 2;

    // move up and left if box is outside screen
	if (targetLeft + targetWidth > screenWidth - margin ) targetLeft = screenWidth - targetWidth - margin; 
	if (targetTop + targetHeight > screenHeight -margin) targetTop = screenHeight - targetHeight - margin;
	
	//move down and right if box is still outside screen
	if (targetLeft < margin) targetLeft = margin;
	if (targetTop < margin) targetTop = margin;

	// if the box is still outside the screen, make it smaller
	if (targetWidth > screenWidth-2*margin) targetWidth = screenWidth-2*margin;
	if (targetHeight > screenHeight-2*margin) targetHeight = screenHeight-2*margin;	 
	
	// finally, impose minimum dimensions
	if (minWidth && targetWidth < minWidth) targetWidth=minWidth;
	if (minHeight && targetHeight < minHeight) targetHeight=minHeight;
    
    MW.css({
    	position:'absolute',
    	overflow:'auto'
    });

    M.css({
        top:targetTop/em + 'em',
        left:targetLeft/em + 'em', 
        width:targetWidth/em + 'em', 
        height:targetHeight/em + 'em'
    });

	M.find('.modal-content,.splash-content').css({
        width:targetWidth/12 + 'em',
        height:targetHeight/12 + 'em'
      });

    M.show();
    MW.fadeIn('slow');
}

function hideModal(leaveBlackAlone)
{
	hideTooltip();
	$('#modal-wrap-'+modalStackTop).remove();	
	modalStackTop--;
    hideBlackScreen();
}


function showSplash(url, params, anchor, deltaLeft, deltaTop,minWidth,minHeight) /* preferred coordinates, min size */
{
    hideTooltip();
    em = 12;
    deltaTop = deltaTop * em;
    deltaLeft = deltaLeft * em;
    targetLeft = anchor.offset().left + deltaLeft;
    targetTop = anchor.offset().top + deltaTop;
    minWidth = minWidth *em;
    minHeight = minHeight * em;

    throbberTop = anchor.offset().top+anchor.height()/2 - 10;
    throbberLeft = anchor.offset().left+anchor.width()/2 -10;

    margin = em/2; 

    W = $(window);
    D = $("body");

    screenWidth = W.width();
    screenHeight = W.height();

    $('#splash-wrap').remove();
    $('#splash').remove();
    D.append('<div id="splash-wrap" style="position:absolute"></div><div id="splash"><img src="/images/7/76/Ajax-throbber.gif"/></div>');

    SW = $('#splash-wrap');
    S = $('#splash');
    SW.click(hideSplash);

    SW.css({
    	background:'black', 
    	opacity:.5,
    //	filter:'alpha(opacity=50)',
    	position:'absolute', 
    	top:0, 
    	left:0, 
    	width:'100%', 
    	height:'100%', 
    	overflow:'hidden',
    	zIndex:1300
    });

    S.css({
        top: throbberTop,
        left: throbberLeft,
        position:'absolute',
        zIndex:1301
    });

    $.get(url,params,function(data,error) {
      if (!$('#splash').length) return false;
      S.css({display:'none'});
      S.html(data);
      targetWidth = S.width();
      targetHeight = S.height();
      if (targetLeft + S.width() > screenWidth) targetLeft = screenWidth - S.width() - margin; 
      if (targetTop + S.height() > screenHeight) targetTop = screenHeight - S.height() -margin;
      if (targetLeft < margin) targetLeft=margin;
      if (targetTop < margin) targetTop=margin;
      S.css({'left':targetLeft,'top':targetTop});
 
      if (targetWidth > screenWidth-2*margin) targetWidth = screenWidth-2*margin;
      if (targetHeight > screenHeight-2*margin) targetHeight = screenHeight-2*margin;	 
      if (minWidth && targetWidth<minWidth) targetWidth=minWidth;
      if (minHeight && targetHeight<minHeight) targetHeight=minHeight;
      
    
      if (targetLeft + targetWidth > screenWidth) targetLeft = screenWidth - targetWidth - margin; 
      if (targetTop + targetHeight > screenHeight) targetTop = screenHeight - targetHeight -margin;
      if (targetLeft < margin) targetLeft=margin;
      if (targetTop < margin) targetTop=margin;

      S.css({
        top:targetTop/12 + 'em',
        left:targetLeft/12 + 'em', 
        width:targetWidth/12 + 'em', 
        height:targetHeight/12 + 'em'
      });
      S.find('.splash-content').css({
        width:targetWidth/12 + 'em',
        height:targetHeight/12 + 'em'
      });
      S.fadeIn('slow');
      setupStuff();
      return S;
    });
}

/*
 *
 *   A J A X  C A L L E R S
 *
 */

function addToCart(link,id)
{
  $('.id-'+id).addClass('selected');
  params={'cart_add':id};
  reloadCart(params);
}

function removeFromCart(link,id)
{
  $('.id-'+id).removeClass('selected');
  $('.compare-collapse.id-'+id).fadeOut('fast', function (n) { $(this).remove() });
  params={'cart_remove':id};
  reloadCart(params);
}

function clearCart(link)
{
  params={'cart_clear':'true'};
  reloadCart(params);
  $('.id').removeClass('selected');
}

function expandCard(link,id)
{  
   if ($(link).parents('.comparecard').length)
     showSplash ( expandUrl, { action:'render', id:id}, $(link).parents('.comparecard'),   0,  0, 40, 30);
   else
     showSplash ( expandUrl, { action:'render', id:id}, $(link).parents('.cart, .card, .flipcard'),  -12, -2, 40, 30);   
}

function compareWith(link,id)
{
   if ($(link).parents('.bigcard').length)
     showSplash ( compareWithUrl, { action:'render', id:id}, $(link).parents('.bigcard'), 0, 0, 40, 30);
   else
     showSplash ( compareWithUrl, { action:'render', id:id}, $(link).parents('.card'), -12, -2, 40, 30);   
}

function compareCart(link)
{
   showSplash ( compareUrl, { action:'render'}, $(link).parents('.cart'), -12, -2, 40, 30);
}

/*
 *
 *   H A N D L E   U P L O A D
 *
 */
function reloadImages(editKey)
{
  $('#editform-images').load( 
     editImagesUrl,   
     {
       editKey:editKey,
       action:'render'
     },
     function()
     {
     	setupStuff();
     	hideBlackScreen();
     }
   );
}
var wgEditKey;
var wgClassifiedId;

function setupUpload()
{
  	if (wgEditKey && wgClassifiedId)
  	{
		$('.link-upload.setup').each(function(n) {
			prepareUpload(this, wgEditKey.toString());
			$(this).removeClass('setup');
		});
		//wgEditKey=false;
		//wgClassifiedId=false;
	}
	else
	{
		$('.link-upload.setup').each(function(n) {
			prepareUpload(this,'');
			$(this).removeClass('setup');
		});
	}
}


function prepareUpload(link, editKey) 
{
  link=$(link);
  anchor=link.parent('.link-upload-wrap');
  new AjaxUpload
  ( 
    anchor, 
    {
      action: link.attr("href"),                 
      'name': 'wpUploadFile',
      data: 
      {
        wpSourceType : 'file',
        wpUploadDescription : '',
        wpIgnoreWarning : 'on',
        wpUpload : 'Naloži sliko',
        action:'render'
      },

      onSubmit: function(file, ext) 
      {
	    if (ext.toString().toLowerCase()=='jpg' || ext.toString().toLowerCase()=='jpeg') 
	    {
	    	showBlackScreen(anchor.offset().left,anchor.offset().top);
 	    	return true;
	    }
	    alert ('Izbrati morate datoteko .jpg ali .jpeg! Poskusite znova.','Avto123.si');
	    return false;
      },
      onComplete: function(file, response) 
      {
        reloadImages(editKey);
        hideBlackScreen();
      },
      onSuccess: function(file, response) 
      {
      },
      onError: function(file, response) 
      {
      }
    }
  );
};


/*
 *
 *   M A I N   S E T U P   C A L L
 *
 */ 

$(document).ready( function()
{
  setupPage();
});

/* addOnloadHook(setupPage); */


/* GALLERIA */

