(function($) {  
	var self = null;
	$.fn.news = function(feed, opt) {	
		return this.each(function(){ new $.news(this, feed, opt);});
	};
	$.news=function(el, feed, opt){    
		var self = this;
		self.el = $('<ul>').appendTo(el);
		self.s= $.extend(
			{
				type: 'json',
				view : 'inline',
				header: 'Fronter International News',
				more: 'Read more...',
				less: 'Hide...',
				animate: false,
				showdesc: false,
				limitdesc: 120,
				descend: '...',
				imgwidth: 200,
				imgheight: 200,
				newslimit: 5,
				open_ext: true
			}, 
		opt ); 
		

		$('<h2>'+self.s.header+'</h2>').prependTo(el);
		self.s.myWidth = self.el.width();

		var feeded = 0;
		if(self.s.type === 'json'){
			if(typeof(feed)==='object'){
				// Just putting out the markup based on the feed
				$.each(feed, function(k,v){
					if(v.title && (feeded<self.s.newslimit && self.s.newslimit !== 0)){
						var id = v.id?v.id:'id'+k;
	
						var markup = '';
						var desc   = '';
						var show   = false; // Should we use Read more / Hide text..( also used in long description to maybe show "HIDE"
						// Check if we need descriptions for the news:
						if ( self.s.showdesc || self.s.limitdesc>0 ){
							// Special handling of <p> and </p> tags, should give at least 1 space, #112490
							desc = v.news.replace(/<\/?p/ig, " $&");
							desc = $( desc ).text();
							if (desc.length>self.s.limitdesc){
								show  = true;
								desc = desc.substring(0, self.s.limitdesc) + self.s.descend +'<p>'+self.s.more+'</p>';
							}
							desc = '<div class="news-desc">'+ desc +'</div>';
						}
						var spic="";
						if ( v.image ){
							spic ='<div class="news-image-short"><img src="" id="sp_' +id +'"/></div>'; 
						}
						var shortnews = '<div class="news-short">'+spic+'<h3>' + v.title +'</h3>' + desc +'</div>';;

						var fpic ='';
						if( v.image ){
							fpic = '<div class="news-image-full"><img src="" id="fp_' +id+'"/></div>' ;
						}
						var fullnews = '<div class="news-full">'+fpic+'<div class="news-full-text"><h3>'+v.title+'</h3>'+v.news +'<a href="#">' ;
						fullnews = fullnews + (show? self.s.less:'') + '</a></div></div>' ;
						var markup =  '<li class="news-item"><div class="news-container" id="news_'+ id + '">' + fullnews + shortnews + '</div></li>' ;
						$(markup).appendTo(self.el);
					
						if(v.image){
							var img = new Image();
							img.onload = function() {
								var fp =$('#fp_' + id );
								var sp =$('#sp_' + id );
								if ( img.width > (self.s.myWidth/2) ){        // Is picture width > 50%
									fp.parent().removeClass("news-image-full");
									fp.parent().removeClass("news-image-full-bigpic");
								
									// Possible re order hte DIVS so that the TITLE comes BEFORe the picture..
									var heading = fp.parent().parent().find("h3");
									fp.parent().before( heading );
								}
				                                var e2='';
								if ( img.width > self.s.myWidth-10 ){
									fp.attr("width", self.s.myWidth );
								}
								fp.attr( "src",  img.src);
								//e = '<div class="' + c +'"><img src="'+v.image+'"' +e2+'/></div>' ;

								// examine the short description picture..
				                                var scale=0;
								var hscale=0;
                                				if (img.width > self.s.imgwidth){
                                        				scale = img.width / self.s.imgwidth;
                                				} 
                                				if (img.height > self.s.imgheight ){
                                        				var hscale = img.height / self.s.imgheight;
                                				} 
								if (scale<hscale) {
									sp.attr("height", self.s.imgheight );
								}else{
									if(scale) sp.attr("width", self.s.imgwidth );
								}
								sp.attr("src", img.src );
							};
							img.src = v.image;
						}

						// Make a callback using the load javascript..
						feeded++;
					}
				});
			} 
		}else if(self.s.type === 'xml'){
		//console.log(feed);
		//console.log(self.s.showdesc)
			var rssfeed = self.xml(feed);
			$.each($(rssfeed).find('item'), function(k,v){
				if((feeded<self.s.newslimit && self.s.newslimit !== 0)){
				var markup = '<li class="news-item"><div class="news-container" id="news_'+
						 	(v.id ? v.id : 'id'+k) +
							'"><h3>'+$(v).find('title').text()+' <span class="rss-read-more">'+self.s.more+'</span></h3>' +
							'<div class="news-content" style="display: none">' +
							$(v).find('description').text() +' <a href="#">' + (self.s.less) +'</a></div></div></li>';
        		(self.s.open_ext ? $(markup).css('cursor', 'pointer').click(function(e){window.open($(v).find('link').text(), 'newsitem');}).appendTo(self.el) : $(markup).appendTo(self.el));
				feeded++;
			}
			});
		}
		$(".news-item:odd").addClass('odd');
		// So we have news, what happens with the news ?

			switch(self.s.view){
					case 'inline':
					$('.news-full').hide(); 
					$('.news-short').show();

					if(!self.s.open_ext){
					$('.news-item').css('cursor', 'pointer').click(function(e){
						if($(this).find('.news-full:hidden').length){
							// Compact all others NEWS that are shown in full format; if any are.
							var prev = $('.news-selected');
							prev.removeClass('news-selected');
							prev.find('.news-full:visible').hide(self.s.animate);
							prev.find('.news-short:hidden').show();

							$(this).addClass('news-selected');
							$(this).find('.news-short').hide();
							$(this).find('.news-full').show(self.s.animate);
						}else{
							// If you pressed an elements allready selected, then just "compact" that element
							$('.news-selected').removeClass('news-selected');
							$(this).find('.news-short').show();
							$(this).find('.news-full').hide(self.s.animate);
						}
					});
					}
					break;
				case 'window':
					if(!self.s.open_ext){
				    $('.news-container').each(function(){
						var ref= $(this).attr('id');
						$(this).find('h3').clone().insertBefore(this).wrapInner('<a href="#'+ref+'" class="zoom"></a>');
							if(self.s.showdesc && (self.s.limitdesc>0)){
								 $(this).find('.news-desc').insertBefore(this); 
							} 
						});
					$('.zoom').fancyZoom({width: 600});  
					}
					break;
			}
		// Check for directly linked news
		if(document.location.hash && document.location.hash.substring(0,5)==='#news'){
			if(self.s.view === 'inline'){
				$(document.location.hash).addClass('news-selected').find('.news-content').show();
			}else{
				$('[href="'+document.location.hash+'"]').trigger('click');
			}
		}
		$('<p>'+document.location.hash+'</p>').appendTo('body');
	};
	 $.news.fn = $.news.prototype = {
			news: '0.0.1'
		};
		$.news.fn.extend = $.news.extend = $.extend;
		$.news.fn.extend({
			xml: function(strXML){
				if (window.DOMParser) {
					try {
						// seems to fail in some of the newer firefox version (3)
						return jQuery(new DOMParser().parseFromString(strXML, "text/xml"));
					} catch (ex) {
						return jQuery(strXML);
					}
				} else if (window.ActiveXObject) {
					var doc = new ActiveXObject("Microsoft.XMLDOM");
					doc.async = "false";
					doc.loadXML(strXML);
					return jQuery(doc);
				} else {
					return jQuery(strXML);
				}   
		 	   
			}
		});
})(jQuery);


(function($){
$.fn.fancyZoom = function(options){  
  var self = this;
  this.opt = $.extend({
		heading: 'This newsfeed heading',
		next: 'Next',
		prev: 'Previous',
		sep: ' | '
	}, options);
  var options   = options || {};
  var directory = 'images';
  var zooming   = false;

  if ($('#zoom').length == 0) {
    var ext = $.browser.msie ? 'gif' : 'png';
    var html = '<div id="zoom" style="display:none;"> \
                  <table id="zoom_table" style="border-collapse:collapse; width:100%; height:100%;"> \
                    <tbody> \
                      <tr> \
                        <td class="tl" style="background:url(' + directory + '/tl.' + ext + ') 0 0 no-repeat; width:20px; height:20px; overflow:hidden;" /> \
                        <td class="tm" style="background:url(' + directory + '/tm.' + ext + ') 0 0 repeat-x; height:20px; overflow:hidden;" /> \
                        <td class="tr" style="background:url(' + directory + '/tr.' + ext + ') 100% 0 no-repeat; width:20px; height:20px; overflow:hidden;" /> \
                      </tr> \
                      <tr> \
                        <td class="ml" style="background:url(' + directory + '/ml.' + ext + ') 0 0 repeat-y; width:20px; overflow:hidden;" /> \
                        <td class="mm" style="background:#fff; vertical-align:top; padding:10px;"> \
                          <div id="zoom_content"> \
                          </div> \
                        </td> \
                        <td class="mr" style="background:url(' + directory + '/mr.' + ext + ') 100% 0 repeat-y;  width:20px; overflow:hidden;" /> \
                      </tr> \
                      <tr> \
                        <td class="bl" style="background:url(' + directory + '/bl.' + ext + ') 0 100% no-repeat; width:20px; height:20px; overflow:hidden;" /> \
                        <td class="bm" style="background:url(' + directory + '/bm.' + ext + ') 0 100% repeat-x; height:20px; overflow:hidden;" /> \
                        <td class="br" style="background:url(' + directory + '/br.' + ext + ') 100% 100% no-repeat; width:20px; height:20px; overflow:hidden;" /> \
                      </tr> \
                    </tbody> \
                  </table> \
                  <a href="#" title="Close" id="zoom_close" style="position:absolute; top:0; left:0;"> \
                    <img src="' + directory + '/closebox.' + ext + '" alt="Close" style="border:none; margin:0; padding:0;" /> \
                  </a> \
                </div>';

    $('body').append(html);

    $('html').click(function(e){if($(e.target).parents('#zoom:visible').length == 0) hide();});
    $(document).keyup(function(event){
        if (event.keyCode == 27 && $('#zoom:visible').length > 0) hide();
    });

    $('#zoom_close').click(hide);
  }

  var zoom          = $('#zoom');
  var zoom_table    = $('#zoom_table');
  var zoom_close    = $('#zoom_close');
  var zoom_content  = $('#zoom_content');
  var middle_row    = $('td.ml,td.mm,td.mr');
	
	
  this.each(function(i) {
    $($(this).attr('href')).hide();
    $(this).click(show);
  });

  return this;

  function show(e) {
    if (zooming) return false;
		zooming         = true;
	$('.news-selected').removeClass('news-selected');
	$(this).addClass('news-selected');

	var content_div = $($(this).attr('href'));
  	var zoom_width  = options.width;
	var zoom_height = options.height;

	var width       = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
  	var height      = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
  	var x           = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
  	var y           = window.pageYOffset || (window.document.documentElement.scrollTop || window.document.body.scrollTop);
  	var window_size = {'width':width, 'height':height, 'x':x, 'y':y}

		var width              = (zoom_width || content_div.width()) + 60;
		var height             = (zoom_height || content_div.height()) + 60;
		var d                  = window_size;

		// ensure that newTop is at least 0 so it doesn't hide close button
		var newTop             =  60; //Math.max((d.height/2) - (height/2) + y, 0);
		var newLeft            = (d.width/2) - (width/2);
		var curTop             = e.pageY;
		var curLeft            = e.pageX;

		zoom_close.attr('curTop', curTop);
		zoom_close.attr('curLeft', curLeft);
		zoom_close.attr('scaleImg', options.scaleImg ? 'true' : 'false');

    $('#zoom').hide().css({
			position	: 'absolute',
			top				: curTop + 'px',
			left			: curLeft + 'px',
			width     : '1px',
			height    : '1px'
		});

    fixBackgroundsForIE();
    zoom_close.hide();

    if (options.closeOnClick) {
      $('#zoom').click(hide);
    }

		if (options.scaleImg) {
  		zoom_content.html(content_div.html());
  		$('#zoom_content img').css('width', '100%');
		} else {
		  zoom_content.html('');
		}

    $('#zoom').animate({
      top     : newTop + 'px',
      left    : newLeft + 'px',
      opacity : "show",
      width   : width,
      height  : height
    }, 0, null, function() {
      if (options.scaleImg != true) {
    		zoom_content.html(content_div.html());
  		}
			unfixBackgroundsForIE();
			zoom_close.show();
			zooming = false;
    })
    return false;
  }

  function hide() {
    if (zooming) return false;
		zooming         = true;
	  $('#zoom').unbind('click');
		fixBackgroundsForIE();
		if (zoom_close.attr('scaleImg') != 'true') {
  		zoom_content.html('');
		}
		zoom_close.hide();
		$('#zoom').animate({
      top     : zoom_close.attr('curTop') + 'px',
      left    : zoom_close.attr('curLeft') + 'px',
      opacity : "hide",
      width   : '1px',
      height  : '1px'
    }, 0, null, function() {
      if (zoom_close.attr('scaleImg') == 'true') {
    		zoom_content.html('');
  		}
      unfixBackgroundsForIE();
			zooming = false;
    });
    return false;
  }

  function switchBackgroundImagesTo(to) {
    $('#zoom_table td').each(function(i) {
      var bg = $(this).css('background-image').replace(/\.(png|gif|none)\"\)$/, '.' + to + '")');
      $(this).css('background-image', bg);
    });
    var close_img = zoom_close.children('img');
    var new_img = close_img.attr('src').replace(/\.(png|gif|none)$/, '.' + to);
    close_img.attr('src', new_img);
  }

  function fixBackgroundsForIE() {
    if ($.browser.msie && parseFloat($.browser.version) >= 7) {
      switchBackgroundImagesTo('gif');
    }
	}

  function unfixBackgroundsForIE() {
    if ($.browser.msie && $.browser.version >= 7) {
      switchBackgroundImagesTo('png');
    }
	}
}
})(jQuery);


jQuery.fn.truncate = function( max, settings ) {
    settings = jQuery.extend( {
        chars: /\s/,
        trail: [ "...", "" ]
    }, settings );
    var myResults = {};
    var ie = $.browser.msie;
    function fixIE( o ) {
        if ( ie ) {
            o.style.removeAttribute( "filter" );
        }
    }
    return this.each( function() {
        var $this = jQuery(this);
        var myStrOrig = $this.html().replace( /\r\n/gim, "" );
        var myStr = myStrOrig;
        var myRegEx = /<\/?[^<>]*\/?>/gim;
        var myRegExArray;
        var myRegExHash = {};
        var myResultsKey = $("*").index( this );
        while ( ( myRegExArray = myRegEx.exec( myStr ) ) != null ) {
            myRegExHash[ myRegExArray.index ] = myRegExArray[ 0 ];
        }
        myStr = jQuery.trim( myStr.split( myRegEx ).join( "" ) );
        if ( myStr.length > max ) {
            var c;
            while ( max < myStr.length ) {
                c = myStr.charAt( max );
                if ( c.match( settings.chars ) ) {
                    myStr = myStr.substring( 0, max );
                    break;
                }
                max--;
            }
            if ( myStrOrig.search( myRegEx ) != -1 ) {
                var endCap = 0;
                for ( eachEl in myRegExHash ) {
                    myStr = [ myStr.substring( 0, eachEl ), myRegExHash[ eachEl ], myStr.substring( eachEl, myStr.length ) ].join( "" );
                    if ( eachEl < myStr.length ) {
                        endCap = myStr.length;
                    }
                }
                $this.html( [ myStr.substring( 0, endCap ), myStr.substring( endCap, myStr.length ).replace( /<(\w+)[^>]*>.*<\/\1>/gim, "" ).replace( /<(br|hr|img|input)[^<>]*\/?>/gim, "" ) ].join( "" ) );
            } else {
                $this.html( myStr );
            }
            myResults[ myResultsKey ] = myStrOrig;
            $this.html( [ "<div class='truncate_less'>", $this.html(), settings.trail[ 0 ], "</div>" ].join( "" ) )
            .find(".truncate_show",this).click( function() {
                if ( $this.find( ".truncate_more" ).length == 0 ) {
                    $this.append( [ "<div class='truncate_more' style='display: none;'>", myResults[ myResultsKey ], settings.trail[ 1 ], "</div>" ].join( "" ) )
                    .find( ".truncate_hide" ).click( function() {
                        $this.find( ".truncate_more" ).css( "background", "#fff" ).fadeOut( "normal", function() {
                            $this.find( ".truncate_less" ).css( "background", "#fff" ).fadeIn( "normal", function() {
                                fixIE( this );
                                $(this).css( "background", "none" );
                            });
                            fixIE( this );
                        });
                        return false;
                    });
                }
                $this.find( ".truncate_less" ).fadeOut( "normal", function() {
                    $this.find( ".truncate_more" ).fadeIn( "normal", function() {
                        fixIE( this );
                    });
                    fixIE( this );
                });
                jQuery(".truncate_show",$this).click( function() {
                    $this.find( ".truncate_less" ).css( "background", "#fff" ).fadeOut( "normal", function() {
                        $this.find( ".truncate_more" ).css( "background", "#fff" ).fadeIn( "normal", function() {
                            fixIE( this );
                            $(this).css( "background", "none" );
                        });
                        fixIE( this );
                    });
                    return false;
                });
                return false;
            });
        }
    });
};

