(function() {
    var window = this,
    undefined, _js = window.js;

    //object initializarion
    js = window.js = function(selector) {
        return new jsObject(selector);
    };

    //the custom javascript object
    jsObject = function(selector) {

        this.jsReady = function(func) {
            var oldonload = window.onload;
            if (typeof window.onload != 'function') {
                window.onload = func;
            } else {
                window.onload = function() {
                    if (oldonload) {
                        oldonload();
                    }
                    func();
                };
            }
        };


var currenthash=window.location.hash;

        //tsSliderV2 = tsSlider
        this.categorytsSlider = function(options) {
		/*$(window).hashchange( function(e) {
  		
		
		
		

	
	if (document.systemchangeform.systemhashchange.value=='false'){
			if (document.systemchangeform.supersystemhashchange.value=='true'){
		      // console.log('found super exception');
			   document.systemchangeform.supersystemhashchange.value='false';
			document.systemchangeform.systemhashchange.value='false';
			}else{
			document.systemchangeform.supersystemhashchange.value='false';
			document.systemchangeform.systemhashchange.value='false';
			///	console.log('actual browser change');
			}
		}else{
			document.systemchangeform.supersystemhashchange.value='false';
			document.systemchangeform.systemhashchange.value='false';
		}
				
				
				
				
		});*/
		
		
	
		
			
        if (typeof options.thepage==='undefined'){
			//alert('this'); 
			var thepage  = 0;
			var cpage=0; 
		}else{ 
	//	alert('that');
		 var thepage = (options.thepage*16);  if (thepage>0){ thepage=thepage-16; } var cpage=options.thepage;
		// alert(cpage);
		  } 
		
	
		
            var itemCache = [];
            var itemCounter = 0;
            var allLoaded = false;
            var padding = 5;
            var mCorrection = 4;
            var cache = options.cache;
            var count = 0;
            var hideLeft = true;
            var hideRight = false;
            var update = true;
            var clicked = false;
            var circleItems = true;
            var htimeout = 50;
            var maxItem = 0;
            var isover = false;
            var ttimeout = null;
            var dwrap = $(document.createElement("div")).width(options.container.width - (mCorrection * 2)).height(options.container.height).css({
                'float': 'left',
                'overflow': 'hidden',
                'margin-left': mCorrection + 'px',
                'position':'relative'
            });
            var dscroll = $(document.createElement("div")).width(options.container.width).height(options.container.height).css({
                'float': 'left',
                'overflow': 'hidden'
            }).mouseleave(function() {
                isover = false;
                if (!clicked) {
                    update = true;
                    ttimeout = setTimeout(function() {
                        hideArrow();
                    },
                    htimeout);
                }
            }).mouseenter(function() {
                isover = true;
                if(ttimeout !== null){
                    clearTimeout(ttimeout);
                }
                if (!clicked) {
                    update = true;
                    showArrow();
                }
            }).hover(function(){
                //isover = true;
                });
            dwrap.append(dscroll);
            $(selector).append(dwrap);
            $(selector).css('overflow', 'hidden');
            $(dwrap).animate({
                scrollLeft: 0
            },
            0);

            var hideArrow = function() {
                if (update) {
                    left.hide();
                    right.hide();
                }
            };

            var showArrow = function() {
                if (update) {
                    if (!hideLeft) left.show();
                    if (!hideRight) right.show();
                }
            };
            //fetch items and call to add items
            var fetchItems = function(url, start, limit, callback,initialLoad) {
				
				
			
                $.ajax({
                    type: 'get',
                    url: url + (isUrlClean(url) ? "?": "&") + "start=" + start  +"&limit=" + limit ,
                    success: function(html) {
                        $(dwrap).css({
                            'background-image':''
                        });
                        try {
                            data = JSON.parse(html);
                        } catch(x) {
                            try{
                                data = $.evalJSON(html)
                            }catch(y){
                                //alert(url);
                                return;
                            }
                        }

                        if(data == null || data.length == 0){
                            return;
                        }
                        count += data.length;
                        callback(data, limit);

                    }
                });
            };

            var getRandom = function(min, max){
                var ran = Math.random();
                ran = (ran*(max - min)) + min;
                return Math.round(ran);
            };

            var addItems = function(data, needed) {
                var output = '';
                for (var i = 0; i < data.length; i++) {
                    if(typeof(data[i]) == 'undefined')
                        continue;
                    if ((i % cache) == 0 && i > 0) {
                        output += '</div>';
                    }
                    if (i % cache == 0) {
                        output += '<div class="quad" style="top:0px; float:left;height:' + options.container.height + 'px; width:' + options.container.width + 'px;">';
                    }
                    itemCache[itemCache.length] = data[i];
                    output += options.buildCallback(data[i], options.item);
                }
                maxItem = parseInt(data[0].pool);
                if(typeof(data[0]) !== 'undefined' && typeof(data[0].pool) !== 'undefined'){
                    if (itemCache.length >= maxItem) {
                        allLoaded = true;
                    }
                }
                
                if(allLoaded) {
                    hideRight = true;
                    //change left top
                    var prev = parseInt(left.css('top').substring(0,left.css('top').length - 2));
                    prev += 60;
                    left.css('top',prev);
                    right.hide();
                }
                var cc;
                var ran = 0;
                if (circleItems) {
                    if (data.length < needed) {
                        cc = needed - data.length;
                        count += cc;
                        while ((cc--) > 0) {
                            ran = getRandom(0,maxItem - 1);
                            output += options.buildCallback(itemCache[ran], options.item);
                            //itemCounter++;
                            //itemCounter = itemCounter == itemCache.length ? 0 : itemCounter;
                        }
                    }else if((data.length % needed) !== 0){
                        var extra = data.length % needed;
                        cc = needed - extra;
                        count += cc;
                        while ((cc--) > 0) {
                            ran = getRandom(0,maxItem - 1);
                            //changed to get random item
                            output += options.buildCallback(itemCache[ran], options.item);
                            //itemCounter++;
                            //output += options.buildCallback(itemCache[itemCounter++], options.item);
                            //itemCounter = itemCounter == itemCache.length ? 0 : itemCounter;
                        }
                    }
                } else {
                    if (data.length < needed) {
                        count += (needed - data.length);
                    }
                }

                dscroll.width((count / cache) * options.container.width);
                output += '</div>';
                dscroll.append(output);
				/*
				
				horrible hack
				*/
				
				$('a.modal').click(function(event)
	{
		event.preventDefault();
		var link = $(this).attr('href');

		//Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();

		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});

		//transition effect
		$('#mask').fadeIn(1000);
		$('#mask').fadeTo("slow",0.8);

		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();

		$("#dialog iframe").attr("src", $(this).attr("href"));

		var ScrollTop = document.body.scrollTop;


if (ScrollTop == 0)
{
    if (window.pageYOffset)
        ScrollTop = window.pageYOffset;
    else
        ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;}
		$("#dialog").css('top',  winH/2-$("#dialog").height()/2 + ScrollTop );
		$("#dialog").css('left', winW/2-$("#dialog").width()/2);

		$("#dialog").fadeIn(2000);
	});

	$('#mask').click(function (event)
	{
		event.preventDefault();
		closePopup();
	});

				
            };

            var addItemsFromCache = function() {
                var output = '';
                count += cache;
                dscroll.width((count / cache) * options.container.width);

                for (var i = 0; i < cache; i++) {
                    if ((i % cache) == 0 && i > 0) {
                        output += '</div>';
                    }
                    if (i % cache == 0) {

                        output += '<div class="quad" style="top:0px; float:left;height:' + options.container.height + 'px; width:' + options.container.width + 'px;">';
                    }
                    output += options.buildCallback(itemCache[itemCounter++], options.item);
                    itemCounter = itemCounter == itemCache.length ? 0 : itemCounter;
                }
                output += '</div>';
                dscroll.append(output);
            };
            //var addLeft = function(cont) {
            var left = $(document.createElement("div")).css({
                'height': '60px',
                'width': '60px',
                'background-image': "url(" + (typeof(options.button) == 'undefined' ? "'/images/global/arrows_left.png'": "'" + options.button.left + "'") + ")",
                'background-repeat': 'no-repeat',
                'background-position': 'left',
                'cursor': 'pointer',
                'left': 0 + padding,
                'z-index': 99,
                'top': options.container.height / 2 - 90,
                'position': 'relative',
                'float': 'none'
            }).click(function() {
                clicked = true;
                update = true;
                hideArrow();
				
	
			document.systemchangeform.systemhashchange.value='true';
				window.location.hash="#!/"+(cpage)+"/";
                $(dwrap).animate({
                    scrollLeft: (cpage - 1 < 0 ? 0 : cpage - 1) * options.container.width
                },
                1000,
                function() {
                    cpage--;
					
                    clicked = false;
                    if(hideRight){
                        var prev = parseInt(left.css('top').substring(0,left.css('top').length - 2));
                        prev -= 60;
                        left.css('top',prev);
                    }
                    hideRight = false;

                    if (cpage <= 0) {
                        cpage = 0;
                        hideLeft = true;
                        left.hide();
                    } else {
                        if (isover) {
                            left.show();
                        }
                    }
                    if (isover) {
                        right.show();
                    }
                });
            })
            .hide()
            .mouseenter(function() {
                update = false;
                isover = true;
                if(ttimeout !== null){
                    clearTimeout(ttimeout);
                }
            })
            .mouseleave(function() {
                isover = false;
                if (!clicked) {
                    update = true;
                    ttimeout = setTimeout(function() {
                        if(!isover)
                            hideArrow();
                    },
                    htimeout);
                }
            });

            //var addRight = function(cont) {
            var right = $(document.createElement("div")).css({
                'height': '60px',
                'width': '60px',
                'background-image': "url(" + (typeof(options.button) == 'undefined' ? "'/images/global/arrows_right.png'": "'" + options.button.right + "'") + ")",
                'background-repeat': 'no-repeat',
                'background-position': 'right',
                'left': options.container.width - 60 - padding,
                'cursor': 'pointer',
                'z-index': 99,
                'top': options.container.height / 2 - 30,
                'position': 'relative',
                'float': 'none'
            }).click(function() {
                clicked = true;
                update = true;
                hideArrow();
				
			
				
				
                $(dwrap).animate({
                    scrollLeft: (cpage + 1) * options.container.width
                },
                1000,
                function() {
                    hideLeft = false;
                    cpage++;
                    clicked = false;
                    if (count <= (cache * (cpage + 1))) {
                        if (allLoaded) {
                        //addItemsFromCache();
                        } else {
							
                            fetchItems(options.url, count, cache, addItems);
                        }
                    }
                    if (isover) {
                        if (count <= (cache * (cpage + 1)) && allLoaded) {
                            hideRight = true;
                            //change left top
                            var prev = parseInt(left.css('top').substring(0,left.css('top').length - 2));
                            prev += 60;
                            left.css('top',prev);
                            right.hide();
                        } else {
                            if (isover) {
                                right.show();
                            }
                        }
                        left.show();
                    }
                });
			document.systemchangeform.systemhashchange.value='true';
				window.location.hash="#!/"+(parseInt(cpage)+1)+"/";
            }).hide().mouseenter(function() {
                update = false;
                isover = true;
                if(ttimeout !== null){
                    clearTimeout(ttimeout);
                }
            }).mouseleave(function() {
                isover = false;
                if (!clicked) {
                    update = true;
                    ttimeout = setTimeout(function() {
                        if(!isover)
                            hideArrow();
                    },
                    htimeout);
                }
            });

            var isUrlClean = function(testUrl) {
                var regexS = "[\\?&]";
                var regex = new RegExp(regexS);
                var results = regex.exec(testUrl);
                if (results == null) return true;
                else return false;
            };

            $(selector).append(right);
            $(selector).append(left);
            var imageObj = new Image();
            imageObj.src = '/images/loader.gif';
            $(dwrap).css({
                'background-image':'url("/images/loader.gif")',
                'background-position':'center',
                'background-repeat':'no-repeat'
            });
	
            fetchItems(options.url,thepage, cache * 2, addItems,true);
	
			
		
			
			
        };







    //tsSliderV2 = tsSlider
        this.tsSlider = function(options) {
            var cpage = 0;
            var itemCache = [];
            var itemCounter = 0;
            var allLoaded = false;
            var padding = 5;
            var mCorrection = 4;
            var cache = options.cache;
            var count = 0;
            var hideLeft = true;
            var hideRight = false;
            var update = true;
            var clicked = false;
            var circleItems = true;
            var htimeout = 50;
            var maxItem = 0;
            var isover = false;
            var ttimeout = null;
            var dwrap = $(document.createElement("div")).width(options.container.width - (mCorrection * 2)).height(options.container.height).css({
                'float': 'left',
                'overflow': 'hidden',
                'margin-left': mCorrection + 'px',
                'position':'relative'
            });
            var dscroll = $(document.createElement("div")).width(options.container.width).height(options.container.height).css({
                'float': 'left',
                'overflow': 'hidden'
            }).mouseleave(function() {
                isover = false;
                if (!clicked) {
                    update = true;
                    ttimeout = setTimeout(function() {
                        hideArrow();
                    },
                    htimeout);
                }
            }).mouseenter(function() {
                isover = true;
                if(ttimeout !== null){
                    clearTimeout(ttimeout);
                }
                if (!clicked) {
                    update = true;
                    showArrow();
                }
            }).hover(function(){
                //isover = true;
                });
            dwrap.append(dscroll);
            $(selector).append(dwrap);
            $(selector).css('overflow', 'hidden');
            $(dwrap).animate({
                scrollLeft: 0
            },
            0);

            var hideArrow = function() {
                if (update) {
                    left.hide();
                    right.hide();
                }
            };

            var showArrow = function() {
                if (update) {
                    if (!hideLeft) left.show();
                    if (!hideRight) right.show();
                }
            };
            //fetch items and call to add items
            var fetchItems = function(url, start, limit, callback) {
                $.ajax({
                    type: 'get',
                    url: url + (isUrlClean(url) ? "?": "&") + "start=" + start + "&limit=" + limit,
                    success: function(html) {
                        $(dwrap).css({
                            'background-image':''
                        });
                        try {
                            data = JSON.parse(html);
                        } catch(x) {
                            try{
                                data = $.evalJSON(html)
                            }catch(y){
                                //alert(url);
                                return;
                            }
                        }

                        if(data == null || data.length == 0){
                            return;
                        }
                        count += data.length;
                        callback(data, limit);

                    }
                });
            };

            var getRandom = function(min, max){
                var ran = Math.random();
                ran = (ran*(max - min)) + min;
                return Math.round(ran);
            };

            var addItems = function(data, needed) {
                var output = '';
                for (var i = 0; i < data.length; i++) {
                    if(typeof(data[i]) == 'undefined')
                        continue;
                    if ((i % cache) == 0 && i > 0) {
                        output += '</div>';
                    }
                    if (i % cache == 0) {
                        output += '<div class="quad" style="top:0px; float:left;height:' + options.container.height + 'px; width:' + options.container.width + 'px;">';
                    }
                    itemCache[itemCache.length] = data[i];
                    output += options.buildCallback(data[i], options.item);
                }
                maxItem = parseInt(data[0].pool);
                if(typeof(data[0]) !== 'undefined' && typeof(data[0].pool) !== 'undefined'){
                    if (itemCache.length >= maxItem) {
                        allLoaded = true;
                    }
                }
                
                if(allLoaded) {
                    hideRight = true;
                    //change left top
                    var prev = parseInt(left.css('top').substring(0,left.css('top').length - 2));
                    prev += 60;
                    left.css('top',prev);
                    right.hide();
                }
                var cc;
                var ran = 0;
                if (circleItems) {
                    if (data.length < needed) {
                        cc = needed - data.length;
                        count += cc;
                        while ((cc--) > 0) {
                            ran = getRandom(0,maxItem - 1);
                            output += options.buildCallback(itemCache[ran], options.item);
                            //itemCounter++;
                            //itemCounter = itemCounter == itemCache.length ? 0 : itemCounter;
                        }
                    }else if((data.length % needed) !== 0){
                        var extra = data.length % needed;
                        cc = needed - extra;
                        count += cc;
                        while ((cc--) > 0) {
                            ran = getRandom(0,maxItem - 1);
                            //changed to get random item
                            output += options.buildCallback(itemCache[ran], options.item);
                            //itemCounter++;
                            //output += options.buildCallback(itemCache[itemCounter++], options.item);
                            //itemCounter = itemCounter == itemCache.length ? 0 : itemCounter;
                        }
                    }
                } else {
                    if (data.length < needed) {
                        count += (needed - data.length);
                    }
                }

                dscroll.width((count / cache) * options.container.width);
                output += '</div>';
                dscroll.append(output);
				/*
				
				horrible hack
				*/
				
				$('a.modal').click(function(event)
	{
		event.preventDefault();
		var link = $(this).attr('href');

		//Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();

		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});

		//transition effect
		$('#mask').fadeIn(1000);
		$('#mask').fadeTo("slow",0.8);

		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();

		$("#dialog iframe").attr("src", $(this).attr("href"));

		var ScrollTop = document.body.scrollTop;


if (ScrollTop == 0)
{
    if (window.pageYOffset)
        ScrollTop = window.pageYOffset;
    else
        ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;}
		$("#dialog").css('top',  winH/2-$("#dialog").height()/2 + ScrollTop );
		$("#dialog").css('left', winW/2-$("#dialog").width()/2);

		$("#dialog").fadeIn(2000);
	});

	$('#mask').click(function (event)
	{
		event.preventDefault();
		closePopup();
	});

				
            };

            var addItemsFromCache = function() {
                var output = '';
                count += cache;
                dscroll.width((count / cache) * options.container.width);

                for (var i = 0; i < cache; i++) {
                    if ((i % cache) == 0 && i > 0) {
                        output += '</div>';
                    }
                    if (i % cache == 0) {

                        output += '<div class="quad" style="top:0px; float:left;height:' + options.container.height + 'px; width:' + options.container.width + 'px;">';
                    }
                    output += options.buildCallback(itemCache[itemCounter++], options.item);
                    itemCounter = itemCounter == itemCache.length ? 0 : itemCounter;
                }
                output += '</div>';
                dwrap.append(output);
            };
            //var addLeft = function(cont) {
            var left = $(document.createElement("div")).css({
                'height': '60px',
                'width': '60px',
                'background-image': "url(" + (typeof(options.button) == 'undefined' ? "'/images/global/arrows_left.png'": "'" + options.button.left + "'") + ")",
                'background-repeat': 'no-repeat',
                'background-position': 'left',
                'cursor': 'pointer',
                'left': 0 + padding,
                'z-index': 99,
                'top': options.container.height / 2 - 90,
                'position': 'relative',
                'float': 'none'
            }).click(function() {
                clicked = true;
                update = true;
                hideArrow();

                $(dwrap).animate({
                    scrollLeft: (cpage - 1 < 0 ? 0 : cpage - 1) * options.container.width
                },
                1000,
                function() {
                    cpage--;
                    clicked = false;
                    if(hideRight){
                        var prev = parseInt(left.css('top').substring(0,left.css('top').length - 2));
                        prev -= 60;
                        left.css('top',prev);
                    }
                    hideRight = false;

                    if (cpage <= 0) {
                        cpage = 0;
                        hideLeft = true;
                        left.hide();
                    } else {
                        if (isover) {
                            left.show();
                        }
                    }
                    if (isover) {
                        right.show();
                    }
                });
            })
            .hide()
            .mouseenter(function() {
                update = false;
                isover = true;
                if(ttimeout !== null){
                    clearTimeout(ttimeout);
                }
            })
            .mouseleave(function() {
                isover = false;
                if (!clicked) {
                    update = true;
                    ttimeout = setTimeout(function() {
                        if(!isover)
                            hideArrow();
                    },
                    htimeout);
                }
            });

            //var addRight = function(cont) {
            var right = $(document.createElement("div")).css({
                'height': '60px',
                'width': '60px',
                'background-image': "url(" + (typeof(options.button) == 'undefined' ? "'/images/global/arrows_right.png'": "'" + options.button.right + "'") + ")",
                'background-repeat': 'no-repeat',
                'background-position': 'right',
                'left': options.container.width - 60 - padding,
                'cursor': 'pointer',
                'z-index': 99,
                'top': options.container.height / 2 - 30,
                'position': 'relative',
                'float': 'none'
            }).click(function() {
                clicked = true;
                update = true;
                hideArrow();
console.log((cpage + 1) * options.container.width);
                $(dwrap).animate({
                    scrollLeft: (cpage + 1) * options.container.width
                },
                1000,
                function() {
                    hideLeft = false;
                    cpage++;
                    clicked = false;
                    if (count <= (cache * (cpage + 1))) {
                        if (allLoaded) {
                     //    addItemsFromCache();
                        } else {
                            fetchItems(options.url, count, cache, addItems);
                        }
                    }
                    if (isover) {
                        if (count <= (cache * (cpage + 1)) && allLoaded) {
                            hideRight = true;
                            //change left top
                            var prev = parseInt(left.css('top').substring(0,left.css('top').length - 2));
                            prev += 60;
                            left.css('top',prev);
                            right.hide();
                        } else {
                            if (isover) {
                                right.show();
                            }
                        }
                        left.show();
                    }
                });
            }).hide().mouseenter(function() {
                update = false;
                isover = true;
                if(ttimeout !== null){
                    clearTimeout(ttimeout);
                }
            }).mouseleave(function() {
                isover = false;
                if (!clicked) {
                    update = true;
                    ttimeout = setTimeout(function() {
                        if(!isover)
                            hideArrow();
                    },
                    htimeout);
                }
            });

            var isUrlClean = function(testUrl) {
                var regexS = "[\\?&]";
                var regex = new RegExp(regexS);
                var results = regex.exec(testUrl);
                if (results == null) return true;
                else return false;
            };

            $(selector).append(right);
            $(selector).append(left);
            var imageObj = new Image();
            imageObj.src = '/images/loader.gif';
            $(dwrap).css({
                'background-image':'url("/images/loader.gif")',
                'background-position':'center',
                'background-repeat':'no-repeat'
            });
            fetchItems(options.url, 0, cache * 2, addItems);
        };

///// new ts slider		

//tsSliderV2 = tsSlider
        this.preloadtsSlider = function(options) {
            var cpage = 0;
            var itemCache = [];
            var itemCounter = 0;
            var allLoaded = false;
            var padding = 5;
            var mCorrection = 4;
            var cache = options.cache;
            var count = (options.cache*2);
            var hideLeft = true;
            var hideRight = false;
            var update = true;
            var clicked = false;
            var circleItems = true;
            var htimeout = 50;
            var maxItem = 0;
            var isover = false;
            var ttimeout = null;
			var previousHash = 0;
            var dwrap = $("#"+options.container.divid+" .dwrap");
			var pool=0;
            var dscroll =$("#"+options.container.divid+" .dscroll").mouseleave(function() {
                isover = false;
                if (!clicked) {
                    update = true;
                    ttimeout = setTimeout(function() {
                        hideArrow();
                    },
                    htimeout);
                }
            }).mouseenter(function() {
                isover = true;
                if(ttimeout !== null){
                    clearTimeout(ttimeout);
                }
                if (!clicked) {
                    update = true;
                    showArrow();
                }
            }).hover(function(){
              isover = true;
     
				});
           
		   
		 
		   
		   var scroll_container = $("#scroll_container_"+options.container.divid).hover(function(){
       	
			if (selectboxesinfocus==false){ 
			  document.systemchangeform.keyboard_control.focus();
			}
				});
			
			
			var keyboard_control= $("#keyboard_control").bind("keyup",function(event){
				var left=37;
				var right=39;
				
				event = window.event || event;
				var currentKey = event.which || event.keyCode;
		
		  		if (currentKey==left){
					goLeft();
					}
				if (currentKey==right){
					goRight();
					}
		
				});
		
		var getpage = function(string){
			arr=string.split("=");
			return arr[1];
		}
		
		$(window).bind('hashchange', function() {
		//	console.log(previousHash);
			console.log('('+getpage(previousHash)+')?('+getpage(location.hash)+')');
			if (getpage(previousHash)==undefined && getpage(location.hash)==2){
				console.log('right');
			goRight();
			return true;
			}
			if (getpage(previousHash)==undefined && getpage(location.hash)==undefined){
				console.log('right');
			goLeft();
			return true;
			}
			
			if (getpage(previousHash)<getpage(location.hash)){
				
					console.log('right');
					goRight();
					return true;
			}
			
			if (getpage(previousHash)>getpage(location.hash)){
					console.log('left');
				goLeft();
				return true;
			}
			
			if (getpage(previousHash)==getpage(location.hash)){
					console.log('left');
				goLeft();
				return true;
				
			}
			
			});

				
			/*
			dwrap.append(dscroll);
            $(selector).append(dwrap);
            $(selector).css('overflow', 'hidden');
            $(dwrap).animate({
                scrollLeft: 0
            },
            0);
			*/
            var hideArrow = function() {
                if (update) {
                    left.hide();
                    right.hide();
                }
            };

            var showArrow = function() {
                if (update) {
                    if (!hideLeft) left.show();
                    if (!hideRight) right.show();
                }
            };
            //fetch items and call to add items
            var fetchItems = function(url, start, limit, callback) {
              
			    $.ajax({
                    type: 'get',
                    url: url + (isUrlClean(url) ? "?": "&") + "start=" + start + "&limit=" + limit,
                    success: function(html) {
                        
						$(dwrap).css({
                            'background-image':''
                        });
						
						
                        try {
                            data = JSON.parse(html);
                        } catch(x) {
                            try{
                             
								data = $.evalJSON(html)
                            }catch(y){
                               
                              //  return;
                            }
                        }

                        if(data == null || data.length == 0){
                           // return;
                        }
                        count += data.length;
                        callback(data, limit);
						
						

                    }
                }); 
				
            };

            var getRandom = function(min, max){
                var ran = Math.random();
                ran = (ran*(max - min)) + min;
                return Math.round(ran);
            };

            var addItems = function(data, needed) {
                var output = '';
                for (var i = 0; i < data.length; i++) {
                    if(typeof(data[i]) == 'undefined')
                        continue;
                    if ((i % cache) == 0 && i > 0) {
                        output += '</div>';
                    }
                    if (i % cache == 0) {
                        output += '<div class="quad" style="top:0px; float:left;height:' + options.container.height + 'px; width:' + options.container.width + 'px;">';
                    }
                    itemCache[itemCache.length] = data[i];
                    output += options.buildCallback(data[i], options.item);
                }
                maxItem = parseInt(data[0].pool);
                if(typeof(data[0]) !== 'undefined' && typeof(data[0].pool) !== 'undefined'){
                    if (itemCache.length >= maxItem) {
                        allLoaded = true;
                    }
                }
                
                if(allLoaded) {
                    hideRight = true;
                    //change left top
                    var prev = parseInt(left.css('top').substring(0,left.css('top').length - 2));
                    prev += 60;
                    left.css('top',prev);
                    right.hide();
                }
                var cc;
                var ran = 0;
                if (circleItems) {
                    if (data.length < needed) {
                        cc = needed - data.length;
                        count += cc;
                        while ((cc--) > 0) {
                            ran = getRandom(0,maxItem - 1);
                            output += options.buildCallback(itemCache[ran], options.item);
                            //itemCounter++;
                            //itemCounter = itemCounter == itemCache.length ? 0 : itemCounter;
                        }
                    }else if((data.length % needed) !== 0){
                        var extra = data.length % needed;
                        cc = needed - extra;
                        count += cc;
                        while ((cc--) > 0) {
                            ran = getRandom(0,maxItem - 1);
                            //changed to get random item
                            output += options.buildCallback(itemCache[ran], options.item);
                            //itemCounter++;
                            //output += options.buildCallback(itemCache[itemCounter++], options.item);
                            //itemCounter = itemCounter == itemCache.length ? 0 : itemCounter;
                        }
                    }
                } else {
                    if (data.length < needed) {
                        count += (needed - data.length);
                    }
                }

                dwrap.width((count / cache) * options.container.width);
                output += '</div>';
                dwrap.append(output);
				/*
				
				horrible hack
				*/
				
				$('a.modal').click(function(event)
	{
		event.preventDefault();
		var link = $(this).attr('href');

		//Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();

		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});

		//transition effect
		$('#mask').fadeIn(1000);
		$('#mask').fadeTo("slow",0.8);

		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();

		$("#dialog iframe").attr("src", $(this).attr("href"));

		var ScrollTop = document.body.scrollTop;


if (ScrollTop == 0)
{
    if (window.pageYOffset)
        ScrollTop = window.pageYOffset;
    else
        ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;}
		$("#dialog").css('top',  winH/2-$("#dialog").height()/2 + ScrollTop );
		$("#dialog").css('left', winW/2-$("#dialog").width()/2);

		$("#dialog").fadeIn(2000);
	});

	$('#mask').click(function (event)
	{
		event.preventDefault();
		closePopup();
	});

				
            };

		var goRight= function(times){
			
			 if (times == null){
				times=1; 
			 }
			
				for (i=0;i<times;i++)
					{
						
					
					console.log("cpage="+cpage);
					
			         clicked = true;
                update = true;
                hideArrow();
		
                $(dscroll).animate({
                     scrollLeft: (cpage + 1) * options.container.width
					
                },
                1000,"linear",
                function() {
                   console.log('oli i miss you');
				   console.log( cpage);
					hideLeft = false;
                    cpage++;
                    clicked = false;
					
                 
					   
                      	if (options.item.total>=(count+1)+cache){
                          fetchItems(options.url, count, cache, addItems);
						  
                        }
						console.log('download complete');
					
						 $(dscroll).animate({
                     scrollLeft: (cpage + 1) * options.container.width
					
                },1000);
					
						
						if (options.item.total<(count+1)+(cache*2)){
                 
						  hideRight = true;
                        }else{
							right.show();
							}
                 
                       left.show();
                  
                });
			    } // end of loop
			}
		
				var goLeft= function(){
			      clicked = true;
                update = true;
                hideArrow();
			 
                $(dscroll).animate({
                    scrollLeft: (cpage - 1 < 0 ? 0 : cpage - 1) * options.container.width
                },
                1000,
                function() {
                    cpage--;
                    clicked = false;
                  
                    hideRight = false;

                    if (cpage <= 0) {
                        cpage = 0;
                        hideLeft = true;
                        left.hide();
                    } else {
                        if (isover) {
                            left.show();
                        }
                    }
                    if (isover) {
                        right.show();
                    }
                });
			
			}
		
		
            var addItemsFromCache = function() {
                var output = '';
                count += cache;
                dscroll.width((count / cache) * options.container.width);

                for (var i = 0; i < cache; i++) {
                    if ((i % cache) == 0 && i > 0) {
                        output += '</div>';
                    }
                    if (i % cache == 0) {

                        output += '<div class="quad" style="top:0px; float:left;height:' + options.container.height + 'px; width:' + options.container.width + 'px;">';
                    }
                    output += options.buildCallback(itemCache[itemCounter++], options.item);
                    itemCounter = itemCounter == itemCache.length ? 0 : itemCounter;
                }
                output += '</div>';
                dscroll.append(output);
            };
            //var addLeft = function(cont) {
            var left = $(document.createElement("div")).css({
                'height': '60px',
                'width': '60px',
                'background-image': "url(" + (typeof(options.button) == 'undefined' ? "'/images/global/arrows_left.png'": "'" + options.button.left + "'") + ")",
                'background-repeat': 'no-repeat',
                'background-position': 'left',
                'cursor': 'pointer',
                'left': 0 + padding,
                'z-index': 99,
                'top': (options.container.height / 2 )- 30,
                'position': 'absolute',
                'float': 'none'
            }).click(function() {
             previousHash=location.hash;
			  location.hash = "#page="+(cpage-1);
			 
			  
            })
            .hide()
            .mouseenter(function() {
                update = false;
                isover = true;
                if(ttimeout !== null){
                    clearTimeout(ttimeout);
                }
            })
            .mouseleave(function() {
                isover = false;
                if (!clicked) {
                    update = true;
                    ttimeout = setTimeout(function() {
                        if(!isover)
                            hideArrow();
                    },
                    htimeout);
                }
            });

            //var addRight = function(cont) {
            var right = $(document.createElement("div")).css({
                'height': '60px',
                'width': '60px',
                'background-image': "url(" + (typeof(options.button) == 'undefined' ? "'/images/global/arrows_right.png'": "'" + options.button.right + "'") + ")",
                'background-repeat': 'no-repeat',
                'background-position': 'right',
                'left': options.container.width - 60 - padding,
                'cursor': 'pointer',
                'z-index': 99,
                'top': (options.container.height / 2) - 30,
                'position': 'absolute',
                'float': 'none'
            }).click(function() {
				var hpage;
				 previousHash=location.hash;
				
					hpage=2+cpage; 
				
				
		
       
            }).hide().mouseenter(function() {
                update = false;
                isover = true;
                if(ttimeout !== null){
                    clearTimeout(ttimeout);
                }
            }).mouseleave(function() {
                isover = false;
                if (!clicked) {
                    update = true;
                    ttimeout = setTimeout(function() {
                        if(!isover)
                            hideArrow();
                    },
                    htimeout);
                }
            });

            var isUrlClean = function(testUrl) {
                var regexS = "[\\?&]";
                var regex = new RegExp(regexS);
                var results = regex.exec(testUrl);
                if (results == null) return true;
                else return false;
            };

            $(selector).append(right);
            $(selector).append(left);
            /*
			var imageObj = new Image();
            imageObj.src = '/images/loader.gif';
            $(dwrap).css({
                'background-image':'url("/images/loader.gif")',
                'background-position':'center',
                'background-repeat':'no-repeat'
            });
			*/
        //    fetchItems(options.url, 0, cache * 2, addItems);
		
		
			if (getpage(location.hash)!==undefined){
				gopage=getpage(location.hash);
				console.log("page="+gopage);
				
									var i=0;
				
					goRight(gopage);
					
				
				}
	
		
        };

//// end new ts slider


	 var leavesite = function(theexitlink) {
			
		//event.preventDefault();
		

		
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
		
		var winH = $(window).height();
		var ScrollTop = document.body.scrollTop;

		if (ScrollTop == 0) {
		
			if (window.pageYOffset)
				ScrollTop = window.pageYOffset;
			else
				ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
		}
		
		$("#companyname").text('Trades Madness');		
		$("#leavingpopup").css('top',  winH/2-$("#leavingpopup").height()/2 +ScrollTop );
		
		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		$('#mask').css('position', 'absolute');
		$('#mask').css('top', 0);
		$('#mask').css('left', 0);
		
		//transition effect		
		$('#mask').fadeIn(1000);	
		$('#mask').fadeTo("slow",0.8);
		// black bkg done
		
		$('#leavingpopup').css('display', 'block');
		
		var url = '/js/global/redir-banner.ajax?banner='+theexitlink;

		$.ajax({
			url: url,
			cache: false,
			success: function(response){
				//location.href = response;			//if want to open link in same window
				child1=window.open(response, '_self');	//if want to open link in new window
			
				
				if (!child1) {   
				$('#delaycountdown').html(' 5 ');
				$('.clean_slate_b').show();
			
				setTimeout("$('#delaycountdown').html(' 4 ');",1000);
				setTimeout("$('#delaycountdown').html(' 3 ');",2000);
				setTimeout("$('#delaycountdown').html(' 2 ');",3000);
				setTimeout("$('#delaycountdown').html(' 1 ');",4000);
				setTimeout("location.href = '"+response+"';",4000);
					}else{
					setTimeout("$('#leavingpopup').hide();",2000);
						setTimeout("$('#mask').hide();",2000);
					}
			}
		});
			
	setTimeout("$('#leavingpopup').hide();",2000);
	setTimeout("$('#mask').hide();",2000);	
		}
			
        //the auto scroller
        this.tsSliderV3 = function(options) {
            var itemCache = [];
            var count = 0;
            var total = 0;
            var cpage = 0;
            var allLoaded = false;
            var padding = 5;
            var mwCorrection = 3;
            var mhCorrection = 5;
            var cache = options.cache;
            var pages = [];
            var direction = 'right';
            var tint = null;
            var max = options.max;
            var animation = options.animation = 'slide';
            var circleItems = true;
            var enableClick = true;
            $(selector).width(options.container.width + mwCorrection).height(options.container.height + mhCorrection);
            var dwrap = $(document.createElement("div"))
            .width(options.container.width)
            .height(options.container.height - 50 + mhCorrection)
            .css({
                'float': 'none',
                'overflow': 'hidden',
                'margin-top':'2px'
            }).addClass("scrollerCorner");

            var dwrapV3 = $(document.createElement("div"))
            .width(options.container.width + mwCorrection * 2)
            .height(options.container.height + 8 - 50)
            .css({
                'float': 'none',
                'overflow': 'hidden',
                'top': '0px',
                'position':'absolute',
                'background-position':'-1px 0px',
                'background-repeat':'no-repeat',
                'background-image':'url("'+options.button.background+'")',
                'cursor':'pointer'
            }).addClass("dwrapV3")
			.click(function(e){
				
                if(direction == 'left'){
                  //  window.open(itemCache[cpage].link,"_blank"); 
					leavesite(itemCache[cpage].link);
                }else if(direction == 'right'){
                   
				   leavesite(itemCache[cpage == 0 ? max - 1 : cpage - 1].link);
				  //  window.open(,"_blank"); 
					//console.log(itemCache[cpage == 0 ? max - 1 : cpage - 1].link);
                }
            });

            var dpage = $(document.createElement("div"))
            .width(15 * max + 5 *(max - 1))
            .height(options.paging.height)
            .css({
                'float': 'none',
                'overflow': 'hidden',
                'text-align':'center',
                'margin':'13px auto 0px auto'
            });
            var dscroll = $(document.createElement("div"))
            .width(options.container.width)
            .height(405).css({
                'float': 'left',
                'overflow': 'hidden',
                'margin-top':'1px',
                'margin-left':'1px'
            });

            dwrap.append(dscroll);
            for(var i = 0; i < max; i++){
                pages[i] = $(document.createElement("div"))
                .width(15)
                .height(15)
                .addClass("pageClass")
                .attr({
                    'tag':i
                })
                .css({
                    'float':'left',
                    'border':'none',
                    'cursor':'pointer',
                    'background-image':'url("'+ (i == 0 ? options.button.selected : options.button.regular) + '")',
                    'background-repeat':'no-repeat'
                }).click(function(n){
                    if(enableClick){
                        stopAnimation();
                        var npage = parseInt($(n.currentTarget).attr('tag'));
                        cpage = npage;

                        //npage = direction == 'left' ? npage : total - (npage + 1);
                        if(options.animation == 'fade'){
                            if(typeof(disableAnimation) == 'undefined'){
                                animateScrollerFade(npage);
                            }else if(disableAnimation == false){
                                animateScrollerFade(npage);
                            }
                        }else if(options.animation == 'slide'){
                            if(typeof(disableAnimation) == 'undefined'){
                                animateScrollerSlide(npage);
                            }else if(disableAnimation == false){
                                animateScrollerSlide(npage);
                            }
                        }
                        startAnimation();
                    }
                });
                dpage.append(pages[i]);
                if(i < (max - 1)){
                    dpage.append(
                        $(document.createElement("div"))
                        .width(5)
                        .height(15)
                        .css({
                            'float':'left'
                        })
                        );
                }
            }

            var setCorners = function(rad, c) {
                curvyCorners({
                    tl: {
                        radius: rad
                    },
                    tr: {
                        radius: rad
                    },
                    bl: {
                        radius: rad
                    },
                    br: {
                        radius: rad
                    },
                    antiAlias: true
                },c);
            };

            $(selector).append(dwrap);
            $(selector).append(dpage);
            $(selector).append(dwrapV3);
            $(selector).css('overflow', 'hidden');

            //setCorners(6,".pageClass");
            /*$(dwrap).animate({
				scrollLeft: 0
			},
			0);*/
            //fetch items and call to add items
            var fetchItems = function(url, start, limit, callback) {
                $.ajax({
                    type: 'get',
                    url: url + (isUrlClean(url) ? "?": "&") + "start=" + start + "&limit=" + limit,
                    success: function(html) {
                        $(dwrap).css({
                            'background-image':''
                        });
                        try {
                            data = JSON.parse(html);
                        } catch(x) {
                            data = $.evalJSON(html)
                        }
                        callback(data, limit);
                    }
                });
            };

            var addItems = function(data, needed) {
                var output = '';
                imageObj = new Image();
                total += data.length;
                for (var i = 0; i < data.length; i++) {
                    if ((i % cache) == 0 && i > 0) {
                        output += '</div>';
                    }
                    if (i % cache == 0) {
                        output += '<div class="quad" style="top:0px; float:'+direction+';height:' +
                        (options.container.height - 45) + 'px; width:'
                        + (options.container.width)+ 'px;">';
                    }
                    itemCache[itemCache.length] = data[i];
                    output += options.buildCallback(itemCache[i], options.item);
                    imageObj.src = itemCache[i].image;
                }
                if (total >= max) {
                    allLoaded = true;
                }
                dscroll.width((total) * options.container.width);
                output += '</div>';
                dscroll.append(output);

                cpage = 0;
                setTimeout(function(){
                    animateScrollerSlide(cpage);
                    if(tint == null)
                        startAnimation();
                },2 * 1000);
            };

            var addItemsFromCache = function(i) {
                var output = '';
                total += cache;
                dscroll.width((count + 2) * options.container.width);
                output += '<div class="quad" style="top:0px; float:'+direction+';height:' +
                (options.container.height - 45)
                + 'px; width:' + (options.container.width) + 'px;">';
                output += options.buildCallback(itemCache[i], options.item);
                output += '</div>';
                dscroll.append(output);
            };

            var addAllItemsFromCache = function() {
                var output = '';
                total += itemCache.length;
                for(var i = 0; i < itemCache.length; i++){
                    output += '<div class="quad" style="top:0px; float:'+direction+';height:' +
                    (options.container.height - 45)
                    + 'px; width:' + (options.container.width) + 'px;">';
                    output += options.buildCallback(itemCache[i], options.item);
                    output += '</div>';
                }
                dscroll.width(total * 555);
                dscroll.append(output);
            };

            var isUrlClean = function(testUrl) {
                var regexS = "[\\?&]";
                var regex = new RegExp(regexS);
                var results = regex.exec(testUrl);
                if (results == null) return true;
                else return false;
            };

            var endCallback = function(){
                for(var i = 0; i < max; i++){
                    pages[i].css({
                        'background-image':'url("' + options.button.regular + '")'
                        });
                }
                pages[cpage].css({
                    'background-image':'url("' + options.button.selected + '")'
                    });
                cpage++;
                cpage = cpage % max;
                if(count >= (total - 1)){
                    if (allLoaded) {
                    //addItemsFromCache(cpage >= (max - 1) ? 0: cpage + 1);
                    //addAllItemsFromCache();
                    } else {
                        fetchItems(options.url, total, cache, addItems);
                    }
                }
            };

            var slideToItem = function(index,callback){
                enableClick = false;
                $(dwrap).animate({
                    scrollLeft: (index) * options.container.width
                },
                600,'swing',
                function(){
                    callback();
                    enableClick = true;
                });
            };

            var animateScrollerSlide = function(index){
                if(direction == 'left'){
                    slideToItem(index + 1,endCallback);
                }else if(direction == 'right'){
                    slideToItem(max - (index+1),endCallback);
                }
            };

            var fadeToItem = function(index,callback){
                enableClick = false;
                $(dscroll).fadeOut(500);
                setTimeout(function(){
                    $(dwrap).attr('scrollLeft',index * options.container.width);
                    $(dscroll).fadeIn(500);
                    callback();
                    enableClick = true;
                },500);

            };

            var animateScrollerFade = function(index){
                fadeToItem(index+1,endCallback);
            };

            var stopAnimation = function(){
                if(tint !== null){
                    clearInterval(tint);
                    tint = null;
                }
            };

            var startAnimation = function(){
                tint = setInterval(function(){
                    if(options.animation == 'fade'){
                        if(typeof(disableAnimation) == 'undefined'){
                            animateScrollerFade(cpage);
                        }else if(disableAnimation == false){
                            animateScrollerFade(cpage);
                        }
                    }else if(options.animation == 'slide'){
                        if(typeof(disableAnimation) == 'undefined'){
                            animateScrollerSlide(cpage);
                        }else if(disableAnimation == false){
                            animateScrollerSlide(cpage);
                        }
                    }
                },typeof(options.interval) == 'undefined'? 5000: options.interval );
            };
            var imageObj = new Image();
            imageObj.src = '/images/loader.gif';
            $(dwrap).css({
                'background-image':'url("/images/loader.gif")',
                'background-position':'center',
                'background-repeat':'no-repeat'
            });

            fetchItems(options.url, 0, cache, addItems);
        };

        //the vertical scroller
        this.tsSliderV5 = function(options) {
            var cpage = 0;
            var itemCache = [];
            var itemCounter = 0;
            var allLoaded = false;
            var padding = 5;
            var mCorrection = 2;
            var cache = options.cache;
            var count = 0;
            var hideLeft = true;
            var hideRight = false;
            var update = true;
            var clicked = false;
            var circleItems = true;
            var htimeout = 100;
            var isover = false;
            var ttimeout = null;
            var dwrap = $(document.createElement("div"))
            .width(options.container.width)
            .height(options.container.height - (mCorrection * 2)).css({
                'float': 'left',
                'overflow': 'hidden',
                'margin-left': mCorrection + 'px'
            });
            var dscroll = $(document.createElement("div"))
            .width(options.container.width)
            .height(options.container.height).css({
                'float': 'left',
                'overflow': 'hidden'
            }).mouseleave(function() {
                isover = false;
                if (!clicked) {
                    update = true;
                    ttimeout = setTimeout(function() {
                        hideArrow();
                    },
                    htimeout);
                }
            }).mouseenter(function() {
                isover = true;
                if(ttimeout !== null){
                    clearTimeout(ttimeout);
                }
                if (!clicked) {
                    update = true;
                    showArrow();
                }
            }).hover(function(){
                //isover = true;
                });
            dwrap.append(dscroll);
            $(selector).append(dwrap);
            $(selector).css('overflow', 'hidden');
            $(dwrap).animate({
                scrollTop: 0
            },
            0);

            var hideArrow = function() {
                if (update) {
                    left.hide();
                    right.hide();
                }
            };

            var showArrow = function() {
                if (update) {
                    if (!hideLeft) left.show();
                    if (!hideRight) right.show();
                }
            };
            //fetch items and call to add items
            var fetchItems = function(url, start, limit, callback) {
                $.ajax({
                    type: 'get',
                    url: url + (isUrlClean(url) ? "?": "&") + "start=" + start + "&limit=" + limit,
                    success: function(html) {
                        $(dwrap).css({
                            'background-image':''
                        });
                        try {
                            data = JSON.parse(html);
                        } catch(x) {
                            data = $.evalJSON(html)
                        }
                        count += data.length;
                        callback(data, limit);
                    }
                });
            };

            var addItems = function(data, needed) {
                var output = '';
                for (var i = 0; i < data.length; i++) {
                    if ((i % cache) == 0 && i > 0) {
                        output += '</div>';
                    }
                    if (i % cache == 0) {
                        output += '<div class="quad" style="top:0px; float:left;height:' + options.container.height + 'px; width:' + options.container.width + 'px;">';
                    }
                    itemCache[itemCache.length] = data[i];
                    output += options.buildCallback(data[i], options.item);
                }
                if(typeof(data[0]) !== 'undefined' && typeof(data[0].pool) !== 'undefined'){
                    if (itemCache.length >= parseInt(data[0].pool)) {
                        allLoaded = true;
                    }
                }
                /*if(allLoaded) {
					hideRight = true;
					//change left top
					var prev = parseInt(left.css('left').substring(0,left.css('left').length - 2));
					prev += 17;
					left.css('left',prev);
					right.hide();
				}*/
                var cc;
                if (circleItems) {
                    if (data.length < needed) {
                        cc = needed - data.length;
                        count += cc;
                        while (cc > 0) {
                            output += options.buildCallback(itemCache[itemCounter++], options.item);
                            itemCounter = itemCounter == itemCache.length ? 0 : itemCounter;
                            cc--;
                        }
                    }else if((data.length % needed) !== 0){
                        var extra = data.length % needed;
                        cc = needed - extra;
                        count += cc;
                        while (cc > 0) {
                            output += options.buildCallback(itemCache[itemCounter++], options.item);
                            itemCounter = itemCounter == itemCache.length ? 0 : itemCounter;
                            cc--
                        }
                    }
                } else {
                    if (data.length < needed) {
                        count += (needed - data.length);
                    }
                }
                dscroll.height((count / cache) * options.container.height);
                output += '</div>';
                dscroll.append(output);
            };

            var addItemsFromCache = function() {
                var output = '';
                count += cache;
                dscroll.height((count / cache) * options.container.height);

                for (var i = 0; i < cache; i++) {
                    if ((i % cache) == 0 && i > 0) {
                        output += '</div>';
                    }
                    if (i % cache == 0) {
                        output += '<div class="quad" style="top:0px; float:left;height:' + options.container.height + 'px; width:' + options.container.width + 'px;">';
                    }
                    output += options.buildCallback(itemCache[itemCounter++], options.item);
                    itemCounter = itemCounter == itemCache.length ? 0 : itemCounter;
                }
                output += '</div>';
                dscroll.append(output);
            };
            //var addLeft = function(cont) {
            var left = $(document.createElement("div")).css({
                'height': '33px',
                'width': '38px',
                'background-image': "url(" + (typeof(options.button) == 'undefined' ? "'images/td/uparrow.png'": "'" + options.button.left + "'") + ")",
                'background-repeat': 'no-repeat',
                'background-position': 'left',
                'cursor': 'pointer',
                'left': (options.container.width/2) - 17 ,
                'z-index': 99,
                'top': padding - 35,
                'position': 'relative',
                'float': 'none'
            }).click(function() {
                clicked = true;
                update = true;
                hideArrow();

                $(dwrap).animate({
                    scrollTop: (cpage - 1) * options.container.height
                },
                1000,
                function() {
                    cpage--;
                    clicked = false;
                    if(hideRight){
                        /*var prev = parseInt(left.css('left').substring(0,left.css('left').length - 2));
						prev -= 17;
						left.css('left',prev);*/

                        prev = parseInt(left.css('top').substring(0,left.css('top').length - 2));
                        prev -= 33;
                        left.css('top',prev);
                    }
                    hideRight = false;
                    if (cpage <= 0) {
                        cpage = 0;
                        hideLeft = true;
                        left.hide();
                    } else {
                        if (isover) {
                            left.show();
                        }
                    }
                    if (isover) {
                        right.show();
                    }
                });
            }).hide()
            .mouseenter(function() {
                update = false;
                isover = true;
                if(ttimeout !== null){
                    clearTimeout(ttimeout);
                }
            }).mouseleave(function() {
                isover = false;
                if (!clicked) {
                    update = true;
                    ttimeout = setTimeout(function() {
                        if(!isover)
                            hideArrow();
                    },
                    htimeout);
                }
            });

            //var addRight = function(cont) {
            var right = $(document.createElement("div")).css({
                'height': '33px',
                'width': '38px',
                'background-image': "url(" + (typeof(options.button) == 'undefined' ? "'images/td/downarrow.png'": "'" + options.button.right + "'") + ")",
                'background-repeat': 'no-repeat',
                'background-position': 'right',
                'left': (options.container.width/2) - 17,
                'cursor': 'pointer',
                'z-index': 99,
                'top': padding + options.container.height - 33 - 5 - (mCorrection * 2),
                'position': 'relative',
                'float': 'none'
            }).click(function() {
                clicked = true;
                update = true;
                hideArrow();

                $(dwrap).animate({
                    scrollTop: (cpage + 1) * options.container.height
                },
                1000,
                function() {
                    hideLeft = false;
                    cpage++;
                    clicked = false;
                    if (count <= (cache * (cpage + 1))) {
                        if (allLoaded) {
                        //addItemsFromCache();
                        } else {
                            fetchItems(options.url, count, cache, addItems);
                        }
                    }
                    if ((cpage == (Math.ceil(count/cache)) - 1)&& allLoaded) {
                        hideRight = true;
                        //change left top
                        /*var prev = parseInt(left.css('left').substring(0,left.css('left').length - 2));
							prev += 17;
							left.css('left',prev);*/
                        right.hide();
                        prev = parseInt(left.css('top').substring(0,left.css('top').length - 2));
                        prev += 33;
                        left.css('top',prev);
                    } else {
                        if (isover) {
                            right.show();
                        }
                    }
                    if (isover) {
                        //right.show();
                        left.show();
                    }
                });
            }).hide().mouseenter(function() {
                update = false;
                isover = true;
                if(ttimeout !== null){
                    clearTimeout(ttimeout);
                }
            }).mouseleave(function() {
                isover = true;
                if (!clicked) {
                    update = true;
                    ttimeout = setTimeout(function() {
                        if(!isover)
                            hideArrow();
                    },
                    htimeout);
                }
            });

            var isUrlClean = function(testUrl) {
                var regexS = "[\\?&]";
                var regex = new RegExp(regexS);
                var results = regex.exec(testUrl);
                if (results == null) return true;
                else return false;
            };

            $(selector).append(right);
            $(selector).append(left);
            var imageObj = new Image();
            imageObj.src = '/images/loader.gif';
            $(dwrap).css({
                'background-image':'url("/images/loader.gif")',
                'background-position':'center',
                'background-repeat':'no-repeat'
            });
            fetchItems(options.url, 0, cache * 2, addItems);
        };

        //the parallel vertical scroller
        this.tsSliderV4 = function(options) {
            var cpage = 0;
            var itemCache = [];
            var itemCounter = 0;
            var allLoaded = false;
            var padding = 5;
            var mCorrection = 2;
            var cache = options.cache;
            var count = 0;
            var hideLeft = true;
            var hideRight = false;
            var update = true;
            var clicked = false;
            var circleItems = true;
            var htimeout = 100;
            var isover = false;
            var ttimeout = null;
            var dwrap = $(document.createElement("div"))
            .width(options.container.width)
            .height(options.container.height - (mCorrection * 2)).css({
                'float': 'left',
                'overflow': 'hidden',
                'margin-left': mCorrection + 'px'
            });
            var dscroll = $(document.createElement("div"))
            .width(options.container.width)
            .height(options.container.height).css({
                'float': 'left',
                'overflow': 'hidden'
            }).mouseleave(function() {
                isover = false;
                if (!clicked) {
                    update = true;
                    ttimeout = setTimeout(function() {
                        hideArrow();
                    },
                    htimeout);
                }
            }).mouseenter(function() {
                isover = true;
                if(ttimeout !== null){
                    clearTimeout(ttimeout);
                }
                if (!clicked) {
                    update = true;
                    showArrow();
                }
            }).hover(function(){
                //isover = true;
                });
            dwrap.append(dscroll);
            $(selector).append(dwrap);
            $(selector).css('overflow', 'hidden');
            $(dwrap).animate({
                scrollTop: 0
            },
            0);

            var hideArrow = function() {
                if (update) {
                    left.hide();
                    right.hide();
                }
            };

            var showArrow = function() {
                if (update) {
                    if (!hideLeft) left.show();
                    if (!hideRight) right.show();
                }
            };
            //fetch items and call to add items
            var fetchItems = function(url, start, limit, callback) {
                $.ajax({
                    type: 'get',
                    url: url + (isUrlClean(url) ? "?": "&") + "start=" + start + "&limit=" + limit,
                    success: function(html) {
                        $(dwrap).css({
                            'background-image':''
                        });
                        try {
                            data = JSON.parse(html);
                        } catch(x) {
                            data = $.evalJSON(html)
                        }
                        count += data.length;
                        callback(data, limit);
                    }
                });
            };

            var addItems = function(data, needed) {
                var output = '';
                for (var i = 0; i < data.length; i++) {
                    if ((i % cache) == 0 && i > 0) {
                        output += '</div>';
                    }
                    if (i % cache == 0) {
                        output += '<div class="quad" style="top:0px; float:left;height:' + options.container.height + 'px; width:' + options.container.width + 'px;">';
                    }
                    itemCache[itemCache.length] = data[i];
                    output += options.buildCallback(data[i], options.item);
                }
                if(typeof(data[0]) !== 'undefined' && typeof(data[0].pool) !== 'undefined'){
                    if (itemCache.length >= parseInt(data[0].pool)) {
                        allLoaded = true;
                    }
                }
                /*if(allLoaded) {
					hideRight = true;
					//change left top
					var prev = parseInt(left.css('left').substring(0,left.css('left').length - 2));
					prev += 17;
					left.css('left',prev);
					right.hide();
				}*/
                var cc;
                if (circleItems) {
                    if (data.length < needed) {
                        cc = needed - data.length;
                        count += cc;
                        while (cc > 0) {
                            output += options.buildCallback(itemCache[itemCounter++], options.item);
                            itemCounter = itemCounter == itemCache.length ? 0 : itemCounter;
                            cc--;
                        }
                    }else if((data.length % needed) !== 0){
                        var extra = data.length % needed;
                        cc = needed - extra;
                        count += cc;
                        while (cc > 0) {
                            output += options.buildCallback(itemCache[itemCounter++], options.item);
                            itemCounter = itemCounter == itemCache.length ? 0 : itemCounter;
                            cc--
                        }
                    }
                } else {
                    if (data.length < needed) {
                        count += (needed - data.length);
                    }
                }
                dscroll.height((count / cache) * options.container.height);
                output += '</div>';
                dscroll.append(output);
            };

            var addItemsFromCache = function() {
                var output = '';
                count += cache;
                dscroll.height((count / cache) * options.container.height);

                for (var i = 0; i < cache; i++) {
                    if ((i % cache) == 0 && i > 0) {
                        output += '</div>';
                    }
                    if (i % cache == 0) {
                        output += '<div class="quad" style="top:0px; float:left;height:' + options.container.height + 'px; width:' + options.container.width + 'px;">';
                    }
                    output += options.buildCallback(itemCache[itemCounter++], options.item);
                    itemCounter = itemCounter == itemCache.length ? 0 : itemCounter;
                }
                output += '</div>';
                dscroll.append(output);
            };
            //var addLeft = function(cont) {
            var left = $(document.createElement("div")).css({
                'height': '33px',
                'width': '38px',
                'background-image': "url(" + (typeof(options.button) == 'undefined' ? "'images/td/uparrow.png'": "'" + options.button.left + "'") + ")",
                'background-repeat': 'no-repeat',
                'background-position': 'left',
                'cursor': 'pointer',
                'left': (options.container.width/2) - 17 ,
                'z-index': 99,
                
				'top':options.container.toparrowpos,
                //'top': 65 + padding + options.container.height - 66 - 5 - (mCorrection * 2),
                'position': 'relative',
                'float': 'none'
            }).click(function() {
                clicked = true;
                update = true;
                hideArrow();

                $(dwrap).animate({
                    scrollTop: (cpage - 1) * options.container.height
                },
                1000,
                function() {
                    cpage--;
                    clicked = false;
                    if(hideRight){
                        prev = parseInt(left.css('top').substring(0,left.css('top').length - 2));
                        prev += 33;
                        left.css('top',prev);
                    }
                    hideRight = false;
                    if (cpage <= 0) {
                        cpage = 0;
                        hideLeft = true;
                        left.hide();
                    } else {
                        if (isover) {
                            left.show();
                        }
                    }
                    if (isover) {
                        right.show();
                    }
                });
            }).hide()
            .mouseenter(function() {
                update = false;
                isover = true;
                if(ttimeout !== null){
                    clearTimeout(ttimeout);
                }
            }).mouseleave(function() {
                isover = false;
                if (!clicked) {
                    update = true;
                    ttimeout = setTimeout(function() {
                        if(!isover)
                            hideArrow();
                    },
                    htimeout);
                }
            });

            //var addRight = function(cont) {
            var right = $(document.createElement("div")).css({
                'height': '33px',
                'width': '38px',
                'background-image': "url(" + (typeof(options.button) == 'undefined' ? "'images/td/downarrow.png'": "'" + options.button.right + "'") + ")",
                'background-repeat': 'no-repeat',
                'background-position': 'right',
                'left': (options.container.width/2) - 17,
                'cursor': 'pointer',
                'z-index': 99,
                //'top': padding,
                'top': padding + options.container.height - 33 - 5 - (mCorrection * 2),
                'position': 'relative',
                'float': 'none'
            }).click(function() {
                clicked = true;
                update = true;
                hideArrow();

                $(dwrap).animate({
                    scrollTop: (cpage + 1) * options.container.height
                },
                1000,
                function() {
                    hideLeft = false;
                    cpage++;
                    clicked = false;
                    if (count <= (cache * (cpage + 1))) {
                        if (allLoaded) {
                        //addItemsFromCache();
                        } else {
                            fetchItems(options.url, count, cache, addItems);
                        }
                    }
                    if ((cpage == (Math.ceil(count/cache)) - 1)&& allLoaded) {
                        hideRight = true;
                        right.hide();
                        prev = parseInt(left.css('top').substring(0,left.css('top').length - 2));
                        prev -= 33;
                        left.css('top',prev);
                    } else {
                        if (isover) {
                            right.show();
                        }
                    }
                    if (isover) {
                        //right.show();
                        left.show();
                    }
                });
            }).hide().mouseenter(function() {
                update = false;
                isover = true;
                if(ttimeout !== null){
                    clearTimeout(ttimeout);
                }
            }).mouseleave(function() {
                isover = true;
                if (!clicked) {
                    update = true;
                    ttimeout = setTimeout(function() {
                        if(!isover)
                            hideArrow();
                    },
                    htimeout);
                }
            });

            var isUrlClean = function(testUrl) {
                var regexS = "[\\?&]";
                var regex = new RegExp(regexS);
                var results = regex.exec(testUrl);
                if (results == null) return true;
                else return false;
            };

            $(selector).append(right);
            $(selector).append(left);
            var imageObj = new Image();
            imageObj.src = '/images/loader.gif';
            $(dwrap).css({
                'background-image':'url("/images/loader.gif")',
                'background-position':'center',
                'background-repeat':'no-repeat'
            });
            fetchItems(options.url, 0, cache * 2, addItems);
        };
        //the shadow
        this.tsShadow = function(options){
            /*var dshadow = $(document).createElement('div')
			.height($(selector).height())
			.width($(selector).width())
			.css({
				'border':'solid 1px #ccc',
				'background-color':'#ccc',
				'z-index': parseInt(options.zIndex) - 1
			});
			$(selector).css({
				'z-index': parseInt(options.zIndex)
			});
			$(selector).parent().append(dshadow)*/
            $(selector).dropShadow();
        };

        //the predictor
        this.tsPredictor = function(options){
            var isover = false;
            var hideTimer = null;
            var timeout = 500;
            var visible = false;
            var lastCall = null;
            var upKey = 38;
            var downKey = 40;
            var enterKey = 13;
            var index = 0;
            var total = 0;
            var stext = "";
            //add the onkey up event handler to call the predictor
            var div = $(document.createElement("div"))
            .css({
                height: 'auto',
                width: options.container.width,
                'background-image':'url("'+options.loader+'")',
                'background-color':'#fff',
                border: 'solid 1px #44A8D5',
                padding:0,
                margin: 0,
                top: 28
            })
            .hide()
            .mouseenter(function(){
                isover = true;
            })
            .mouseleave(function(){
                isover = false;
                hideTimer = setTimeout(function(){
                    if(!isover){
                        div.hide();
                        visible = false;
                    }
                },timeout);
            });
            $(selector).parent().append(div);
            $(selector).parent().css({
                position: 'relative',
                'z-index': 999
            });

            var deselectItem = function(index){
                /*var dd = $(".ajax_item").get(index);
				$(dd).css({
					backgroundColor: '#fff',
					color: '#44A8D5',
					cursor:'pointer'
				});*/
                $(".ajax_item").css({
                    backgroundColor: '#fff',
                    color: '#44A8D5',
                    cursor:'pointer'
                });
            };

            var selectItem = function(index){
                var dd = $(".ajax_item").get(index);
                $(dd).css({
                    backgroundColor: '#44A8D5',
                    color: '#fff',
                    cursor:'pointer'
                });
                stext = $(dd).html();
            };

            var buildItem = function(item, dim, ind){
                return $(document.createElement("div"))
                .html(item)
                .attr('tag',ind)
                .addClass("ajax_item")
                .hover(function(){
                    index = parseInt($(this).attr('tag'));
                    //$(this).addClass("selected");
                    deselectItem(0);
                    $(this).css({
                        backgroundColor: '#44A8D5',
                        color: '#fff',
                        cursor:'pointer'
                    });
                })
                .mouseleave(function(){
                    deselectItem(0);
                    //$(this).removeClass("selected");
                    $(this).css({
                        backgroundColor: '#fff',
                        color: '#44A8D5',
                        cursor:'pointer'
                    });
                })
                .click(function(){
                    $(selector).val($(this).html());
                    $(options.form).submit();
                    div.hide();
                });
            };

            var addItems = function(data){
                div.html('');
                if(data == null){
                    return;
                }
                for(var i = 0; i < data.length;i++){
                    div.append(
                        buildItem(
                            data[i],
                            {
                                width: options.container.width,
                                height: 20
                            },
                            i
                            )
                        );
                }
                total = data.length;
                index = 0;
                selectItem(0);
                lastCall = null;
            };

            var fetchItems = function(url,callBack){
                if(lastCall !== null){
                    lastCall.abort();
                }
                lastCall = $.ajax({
                    url: url,
                    dataType: "json",
                    success: function(msg){
                        callBack(msg);
                    }
                });
            };

            var isUrlClean = function(testUrl) {
                var regexS = "[\\?&]";
                var regex = new RegExp(regexS);
                var results = regex.exec(testUrl);
                if (results == null) return true;
                else return false;
            };
            //show the div and update list
            $(selector)
            .keypress(function(n){
                var code = n.which || n.keyCode;
                if(code == enterKey){
                    $(selector).val(stext);
                    $(options.form).submit();
                    div.hide();
                }else if(code == upKey){
                    deselectItem(index);
                    index--;
                    index = index < 0 ? 0: index;
                    selectItem(index);
                }else if(code == downKey){
                    deselectItem(index);
                    index++;
                    index = index >= total ? total - 1 : index;
                    selectItem(index);
                }else{
                    fetchItems(options.url + (isUrlClean(options.url) ? "?" :"&" )+ "q=" + $(n.currentTarget).val() + String.fromCharCode(n.charCode), addItems);
                    if(!visible){
                        div.show();
                        visible = true;
                    }
                }
            })
            .mouseleave(function(){
                isover = false;
                hideTimer = setTimeout(function(){
                    if(!isover){
                        div.hide();
                        visible = false;
                    }
                },timeout);
            })
            .mouseenter(function(){
                isover = true;
            });
        };
        return this;
    };
})();

