/*combination of 
-- login.js
-- menu-slide.js
-- video-direct.js
-- suggest.js
-- hslider.js
*/
/**
* Callback function that displays the content.
*
* Gets called every time the user clicks on a pagination link.
*
* @param {int} page_index New Page index
* @param {jQuery} jq the container with the pagination links as a jQuery object
*/
function pageselectCallback(page_index, jq) {
    // Get number of elements per pagionation page from form
    var items_per_page = 12;
    var max_elem = Math.min((page_index + 1) * items_per_page, jQuery('#ResultList li').length);
    $('#Searchresult').empty();
    var new_content = '';
    // Iterate through a selection of the content and build an HTML string
    for (var i = page_index * items_per_page; i < max_elem; i++) {
        //$('#Searchresult').append($('li.thumb-medium').eq(i).clone());
        $('#Searchresult').append(jQuery('#ResultList li:eq(' + i + ')').clone());
    }

    return false;
}

/** 
* Initialisation function for pagination
*/
function initPagination() {
    $('#Searchresult').empty();
    // count entries inside the hidden content
    var num_entries = jQuery('li.thumb-medium').length;
    // Create content inside pagination element
    $("#Pagination").pagination(num_entries, {
        callback: pageselectCallback,
        items_per_page: 12 // Show only one item per page
    });
    pageselectCallback(0, null);
  
}



$(document).ready(function () {


    //Check Account Number
    $('#npu-account-submit').click(function () {
        //$("#lightbox, #npu-step2-box").fadeOut(300);
        //$('#lightbox, #npu-success-box').fadeIn(300);

        var AccountNo = $('#npu-account-enter').val();
        var ISPID = $('#npu-accounttype').val();

        //alert(AccountNo + " | " + ISPID);

        $.ajax({
            url: "/Account/UpgradePackage",
            data: "AccountNo=" + AccountNo + "&ISPID=" + ISPID,
            type: "POST",
            success: function (data) {
                if (data.success == "true") {
                    if (ISPID < 3) {
                        $("#lightbox, #npu-step2-box").fadeOut(300);
                        $("#lightbox, #npu-elite-step2-box").fadeOut(300);
                        $('#lightbox, #npu-success-box').fadeIn(300);
                    }
                    if (ISPID > 2) {
                        $("#lightbox, #npu-step2-box").fadeOut(300);
                        $("#lightbox, #npu-elite-step2-box").fadeOut(300);
                        $("#lightbox ,#npu-elite-success-box").fadeIn(300);
                    }
                }

                if (data.success == "false") {
                    if (ISPID < 3) {
                        $("#lightbox, #npu-step2-box").fadeOut(300);
                        $("#lightbox, #npu-elite-step2-box").fadeOut(300);
                        $("#error_description").html(data.error);
                        $('#lightbox, #npu-error-box').fadeIn(300);
                    }
                    if (ISPID > 2) {
                        $("#lightbox, #npu-step2-box").fadeOut(300);
                        $("#lightbox, #npu-elite-step2-box").fadeOut(300);
                        $("#error_description").html(data.error);
                        $("#lightbox ,#npu-error-box").fadeIn(300);
                    }
                }
            },
            error: function (data) {
                alert("Error");
            }
        });
    });



    //Check Account Number
    $('#npu-account-submit-elite').click(function () {
        //$("#lightbox, #npu-step2-box").fadeOut(300);
        //$('#lightbox, #npu-success-box').fadeIn(300);

        var AccountNo = $('#npu-account-enter-elite').val();
        var ISPID = $('#npu-accounttype-elite').val();

        //alert(AccountNo + " | " + ISPID);

        $.ajax({
            url: "/Account/UpgradePackage",
            data: "AccountNo=" + AccountNo + "&ISPID=" + ISPID,
            type: "POST",
            success: function (data) {
                if (data.success == "true") {
                    if (ISPID < 3) {
                        $("#lightbox, #npu-step2-box").fadeOut(300);
                        $("#lightbox, #npu-elite-step2-box").fadeOut(300);
                        $('#lightbox, #npu-success-box').fadeIn(300);
                    }
                    if (ISPID > 2) {
                        $("#lightbox, #npu-step2-box").fadeOut(300);
                        $("#lightbox, #npu-elite-step2-box").fadeOut(300);
                        $("#lightbox ,#npu-elite-success-box").fadeIn(300);
                    }
                }

                if (data.success == "false") {
                    if (ISPID < 3) {
                        $("#lightbox, #npu-step2-box").fadeOut(300);
                        $("#lightbox, #npu-elite-step2-box").fadeOut(300);
                        $("#error_description").html(data.error);
                        $('#lightbox, #npu-error-box').fadeIn(300);
                    }
                    if (ISPID > 2) {
                        $("#lightbox, #npu-step2-box").fadeOut(300);
                        $("#lightbox, #npu-elite-step2-box").fadeOut(300);
                        $("#error_description").html(data.error);
                        $("#lightbox ,#npu-error-box").fadeIn(300);
                    }
                }
            },
            error: function (data) {
                alert("Error");
            }
        });
    });



    //Playlist Number
    $('.playlist-count').html($('#user_playlist_container li').size());

    //Set Title
    //display name
    $('div #title_header').html('<h2>' + $("ul.movie-categories-list li").attr('name') + '</h2>');

    //Navigation Active Selection
    var val = ($.url().attr('directory').length < 2 ? "tv" : $.url().segment(1).toLowerCase() + "_nav");
    $("#" + val).addClass("active-nav");

    //Like Button

    $('.favorite-icon').live('click', function () {
        var program_id = $(this).attr('program_id');
        var episode_id = $(this).attr('episode_id');

        $.ajax({
            url: "/Video/SetVideoLikes",
            data: "program_id=" + program_id + "&episode_id=" + episode_id,
            type: "POST",
            success: function (data) {
                $(true);
            },
            error: function (data) {
                alert("Error");
            }
        });
    });


    //Watch-later Button
    $('.playlist-icon').live('click', function () {
        //alert("text");
        var program_id = $(this).attr('program_id');
        var episode_id = $(this).attr('episode_id');

        $.ajax({
            url: "/Video/SetPlaylist",
            data: "program_id=" + program_id + "&episode_id=" + episode_id,
            type: "POST",
            success: function (data) {
                $(true);
                window.location.reload();
            },
            error: function (data) {
                alert("Error");
            }
        });

    });

    //Delete playlist
    $('.delete-icon').live('click', function () {
        var program_id = $(this).attr('program_id');
        var episode_id = $(this).attr('episode_id');

        $.ajax({
            url: "/Video/RemovePlaylist",
            data: "program_id=" + program_id + "&episode_id=" + episode_id,
            type: "POST",
            success: function (data) {
                $(true);


                $.ajax({
                    url: "/Video/GetPlaylist",
                    type: "GET",
                    success: function (data) {
                        if (data.length > 0) {
                            $('#user_playlist_container').html(data);
                            //    hideHoverState();                           
                        }
                        else {
                            $('#user_playlist_container').html("");
                        }
                        $('.playlist-count').html($('#user_playlist_container li').size());
                    },
                    error: function (data) {
                        alert("Error");
                    }
                });

            },
            error: function (data) {
                alert("Error");
            }
        });

    });


    // Expand Panel
    $("#open").live('click', function () {
        $('.video-player-container').css({ "margin-top": "0px", "display": "block" });
        $('.tab-container').css({ "margin-top": "0px", "display": "block" });
        $('.reg-page').css({ "display": "inline-block", "margin-top": "0px" });
        $("#toggle").css({ height: "50px", "background-image": "url(theme/images/lightbox/dd-bg-3x3.jpg)", "background-repeat": "repeat", border: " 1px solid #f3f2f2", "border-bottom": "none", color: "#03c3fb" });
        $(".panel").css({ height: "190px", border: "1px solid #f3f2f2", "margin-bottom": "0px" });
        $(".panel").slideDown("slowest");


        $.ajax({
            url: "/Video/GetPlaylist",
            type: "GET",
            success: function (data) {
                if (data.length > 0) {
                    $('#user_playlist_container').html(data);
                    //alert($('#user_playlist_container li').size());
                    $('.playlist-count').html($('#user_playlist_container li').size());
                    hideHoverState();
                }
                $(".panel").slideDown("slowest");
            },
            error: function (data) {
                alert("Error");
            }
        });

    });

    // Collapse Panel
    $("#close").live('click', function () { $('.video-player-container, .movie-holder').css({ "margin-top": "-40px", "display": "inline-block" }); $('.tab-container').css({ "margin-top": "-40px", "display": "inline-block" }); $("#toggle").animate({ height: "40px" }, 3e3); $('.reg-page').css({ "margin-top": "-40px" }); $("#toggle").css({ "background-image": "none", "background-repeat": "no-repeat", border: "none", color: "#03c3fb" }); $(".panel").slideUp("slowest") });
    // old code
    //    $("#close").click(function () {
    //        $("#toggle").animate({
    //            "height": "40px"
    //        }, 3000);
    //        $("#toggle").css({
    //            "background-image": "none",
    //            "background-repeat": "no-repeat",
    //            "border": "none",
    //            "color": "#03c3fb"
    //        });
    //        $('.content').css({
    //            "margin-top": "-40px"
    //        });
    //        /*$("#toggle").css("background-color","#000");*/
    //        $(".panel").slideUp("slowest");
    //    });

    // Switch buttons from "View Playlist" to "Close Playlist" on click
    $("#toggle a").click(function () {
        $("#toggle a").toggle();
    });

    $("#open").hover(function () {
        $("#toggle span.arrow-left-playlist").addClass("hover") /* Add class of "hover"*/
		.css({
		    "background-position": "-10px 0",
		    "top": "10px"
		}, 200); /* this value of "200" is the speed of how fast/slow this hover animates */

    }, function () {
        $("#toggle span.arrow-left-playlist").removeClass("hover")  /* Remove the "hover" class , then stop animation queue buildup*/
		.css({
		    "background-position": "0 0",
		    "top": "10px"
		});
    });

    // Hover to Close Panel
    $("#close").hover(function () {
        $("#toggle span.arrow-down-playlist").addClass("hover") /* Add class of "hover"*/
		.css({
		    "background-position": "-10px -10px",
		    "top": "10px"
		}, 200); /* this value of "200" is the speed of how fast/slow this hover animates */

    }, function () {
        $("#toggle span.arrow-down-playlist").removeClass("hover")  /* Remove the "hover" class , then stop animation queue buildup*/
		.css({
		    "background-position": "0 -10px",
		    "top": "10px"
		});
    });
    $(".signin").click(function (e) {
        e.preventDefault();
        $("fieldset#signin-menu").toggle();
        $(".signin").toggleClass("menu-open");
    });

    $("fieldset#signin-menu").mouseup(function () {
        return false
    });
    $(document).mouseup(function (e) {
        if ($(e.target).parent("a.signin").length == 0) {
            $(".signin").removeClass("menu-open");
            $("fieldset#signin-menu").hide();
        }
    });
    $('#npu-youmust-login, #npu-youmust-login-email, #npu-youmust-login-password, #video-play-visitor, #youmust-login').click(function () {
        $('#lightbox, #youmust-box').fadeIn(300);
    });
    $('#youmust-close').click(function () {
        $("#lightbox, #youmust-box").fadeOut(300);
        window.location.replace("/Account/Login");
    });
    /////////// PASSWORD RETRIVAL ////////////
    $('#forgot-password-link, #resend-password-link, #flel-resend-password-link, #error-resend-password-link').click(function () {
        $("#lightbox, #youmust-box").fadeOut(300);
        $('#lightbox, #why-box-forgot').fadeIn(300);
        $("fieldset#signin-menu").hide();
    });
    $('#why-close-forgot').click(function () {
        $("#lightbox, #why-box-forgot").fadeOut(300);
        window.location.replace("#");
    });
    $('#why-close-newpass').click(function () {
        $("#lightbox, #why-box-newpass").fadeOut(300);
        window.location.replace("#");
    });
    $('#why-close-pass-error').click(function () {
        $("#lightbox, #why-box-pass-error").fadeOut(300);
        window.location.replace("#");
    });
    /////
    $('#forgot-submit').click(function () {
        $("#lightbox, #why-box-forgot").fadeOut(300);
        $('#lightbox, #loader-box').fadeIn(300);

        $.ajax({
            url: "/Account/ForgotPassword",
            data: "forgot_email=" + $('#forgot_email').val(),
            type: "POST",
            success: function (data) {
                if (data == "true") {
                    $('#lightbox, #loader-box').fadeOut(300);
                    $('#lightbox, #why-box-newpass').fadeIn(300);
                }
                if (data == "false") {
                    $('#lightbox, #loader-box').fadeOut(300);
                    $('#lightbox, #why-box-pass-error').fadeIn(300);
                }
            }
        });
    });

    ///////// POP UP NON-PREMIUM USER ////////
    //// STEP 1 OPEN LIGHTBOX /////////
    $('#npu-step1, #video-play-nonuser').click(function () {
        $('#lightbox, #npu-step1-box').fadeIn(300);
        $("fieldset#signin-menu").hide();
    });
    //// STEP 1 CLOSE LIGHTBOX ////////
    $('#why-close-npustep1, #why-close2-npustep1').click(function () {
        $("#lightbox, #npu-step1-box").fadeOut(300);
        window.location.replace("/");
    });
    //// STEP 2 OPEN LIGHTBOX ////////
    $('#npu-step2').click(function () {
        $("#lightbox, #npu-step1-box").fadeOut(300);
        $('#lightbox, #npu-step2-box').fadeIn(300);
        $("fieldset#signin-menu").hide();
    });


    //// Footer STEP 2 OPEN LIGHTBOX ////////
    $('#npu-step2-footer').click(function () {
        $("#lightbox, #npu-step1-box").fadeOut(300);
        $('#lightbox, #npu-step2-box').fadeIn(300);
        $("fieldset#signin-menu").hide();
    });

    //// STEP 2 CLOSE LIGHTBOX ////////
    $('#why-close-npustep2').click(function () {
        $("#lightbox, #npu-step2-box").fadeOut(300);
        window.location.replace("#");
    });

    ///////// POP UP NON-ELITE USER ////////
    //// STEP 1 OPEN LIGHTBOX /////////
    $('#npu-step1, #video-play-nonuser').click(function () {
        $('#lightbox, #npu-elite-step1-box').fadeIn(300);
        $("fieldset#signin-menu").hide();
    });
    //// STEP 1 CLOSE LIGHTBOX ////////
    $('#why-close-npustep1-elite,why-close2-npustep1-elite').click(function () {
        $("#lightbox,#npu-elite-step1-box").fadeOut(300);
        window.location.replace("#");
    });
    //// STEP 2 OPEN LIGHTBOX ////////
    $('#npu-step2-elite').click(function () {
        $("#lightbox, #npu-elite-step1-box").fadeOut(300);
        $('#lightbox, #npu-elite-step2-box').fadeIn(300);
        $("fieldset#signin-menu").hide();
    });

    //// Footer STEP 2 OPEN LIGHTBOX ////////
    $('#npu-step2-elite-footer').click(function () {
        $("#lightbox, #npu-elite-step1-box").fadeOut(300);
        $('#lightbox, #npu-elite-step2-box').fadeIn(300);
        $("fieldset#signin-menu").hide();
    });

    //// STEP 2 CLOSE LIGHTBOX ////////
    $('#why-close-npustep2-elite').click(function () {
        $("#lightbox, #npu-elite-step2-box").fadeOut(300);
        window.location.replace("#");
    });


    //// SUCCESS LIGHTBOX ////////
    $('#npu-success').click(function () {
        $("#lightbox, #npu-step2-box").fadeOut(300);
        $('#lightbox, #npu-success-box').fadeIn(300);
        $("fieldset#signin-menu").hide();
    });
    //// SUCCESS CLOSE LIGHTBOX ////////
    $('#why-close-npusuccess').click(function () {
        $("#lightbox, #npu-success-box").fadeOut(300);
    });

    //// SUCCESS CLOSE LIGHTBOX ////////
    $('#why-close-npusuccess-elite').click(function () {
        $("#lightbox, #npu-elite-success-box").fadeOut(300);
    });


    //// ERROR LIGHTBOX ////////
    $('#npu-error').click(function () {
        $("#lightbox, #npu-step2-box").fadeOut(300);
        $('#lightbox, #npu-error-box').fadeIn(300);
        $("fieldset#signin-menu").hide();
    });
    //// ERROR CLOSE LIGHTBOX ////////
    $('#why-close-npuerror').click(function () {
        $("#lightbox, #npu-error-box").fadeOut(300);
        window.location.replace("#");
    });
    //// VIEW SUBSCRIPTION OPEN LIGHTBOX ////////
    $('#npu-view-sub').click(function () {
        $("#lightbox, #npu-viewsub-box").fadeIn(300);
        $("fieldset#signin-menu").hide();
    });
    //// VIEW SUBSCRIPTION CLOSE LIGHTBOX ////////
    $('#why-close-npuviewsub').click(function () {
        $("#lightbox, #npu-viewsub-box").fadeOut(300);
        window.location.replace("#");
    });
    //// VIEW SUBSCRIPTION OPEN LIGHTBOX ////////
    $('#npu-viewsub').click(function () {
        $("#lightbox, #npu-step1-box").fadeOut(300);
        $("#lightbox, #npu-viewsub-box").fadeIn(300);
        $("fieldset#signin-menu").hide();
    });
    $('#npu-viewsub-elite').click(function () {
        $("#lightbox, #npu-elite-step1-box").fadeOut(300);
        $("#lightbox, #npu-viewsub-box").fadeIn(300);
        $("fieldset#signin-menu").hide();
    });
    //// VIEW SUBSCRIPTION CLOSE LIGHTBOX ////////
    $('#why-close-npuviewsub').click(function () {
        $("#lightbox, #npu-viewsub-box").fadeOut(300);
        window.location.replace("#");
    });
    //// THANK YOU OPEN LIGHTBOX ////////
    $('#why-thanks').click(function () {
        $("#lightbox, #why-box-thanks").fadeIn(300);
        $("fieldset#signin-menu").hide();
    });
    //// THANKS YOU CLOSE LIGHTBOX ////////
    $('#why-close-thanks').click(function () {
        $("#lightbox, #why-box-thanks").fadeOut(300);
        window.location.replace("#");
    });
    //// ACCOUNT UPDATE ////
    $('#acct-update').click(function () {
        $("#lightbox, #why-box-acct-update").fadeIn(300);
        $("fieldset#signin-menu").hide();
    });
    //// ACCOUNT UPDATE CLOSE ////
    $('#why-close-acct-update').click(function () {
        $('#lightbox, #why-box-acct-update').fadeOut(300);
        window.location.replace('#');
    });
    //// NO NEED LIGHTBOX ////////
    $('#npu-no-need').click(function () {
        $('#lightbox, #npu-prem-box').fadeIn(300);
        $("fieldset#signin-menu").hide();
    });
    //// NO NEED CLOSE LIGHTBOX ////////
    $('#why-close-npuprem').click(function () {
        $("#lightbox, #npu-prem-box").fadeOut(300);
        window.location.replace("#");
    });

    /*----Video redirect script for thumbnails-------*/
    /* FOR SIMULATION PURPOSES ONLY					 */
    /* CheAnneCruz									 */
    /*-----------------------------------------------*/
    //	$('.playbtn').live('click', function(){
    //	if ($('#state').html() == 'L'){ // $('#state') div declared for simulation purposes NL for not logged-in L for logged-in
    //		alert ('logged in');	
    //		if($(this).parent().parent().find('span.type').html() == 'PREMIUM'){ // if logged-in, check if video is for premium users ONLY
    //			alert('video is premium');
    //			if($('.prem-badge img').length == 0){ //check if the user has a premuim account by checking if a premium badge exist
    //				alert('no badge');
    //				window.location.href='nonprem-video.html'; //if not premium, redirect to this page
    //		        return false;
    //			}else{
    //				alert('with badge');
    //				window.location.href='prem-video.html'; //if premium, redirect to this page
    //				return false;
    //			}
    //		}else{ // if the video is not for premium users, the video is FREE!!!!.. :D
    //		alert('video is not premuim');
    //			if($('.prem-badge img').length == 0){ //if user is logged-in, check if the user has a premuim account by checking if a premium badge exist
    //				alert('FREE no badge');
    //				window.location.href='nonprem-free-video.html'; //if not premium, redirect to this page
    //		        return false;
    //			}else{
    //				alert('FREE with badge');
    //				window.location.href='prem-free-video.html'; //if premium, redirect to this page
    //				return false;
    //			}
    //		}
    //	}else{
    //		alert('not logged in');
    //		window.location.href='video.html'; //if not logged-in, regirect to this page
    //		return false;
    //	}
    //	});

    //	$('.small-play').live('click', function(){
    //	if ($('#state').html() == 'L'){ // $('#state') div declared for simulation purposes NL for not logged-in L for logged-in
    //	  alert ('logged in');	
    //		  if($('.prem-badge img').length == 0){ //check if the user has a premuim account by checking if a premium badge exist
    //			  alert('no badge');
    //			  window.location.href='nonprem-video.html'; //if not premium, redirect to this page
    //			  return false;
    //		  }else{
    //			  alert('with badge');
    //			  window.location.href='prem-video.html'; //if premium, redirect to this page
    //			  return false;
    //		  }
    //	}else{
    //		alert('not logged in');
    //		window.location.href='video.html'; //if not logged-in, regirect to this page
    //		return false;
    //	}
    //    });


    var hSlider = function () {
        var self = this;
        this._init = function (element, options) {

            // Passed in options and default options are mixed
            this.options = $.extend({}, this._settings, options);

            // Save the element reference
            this.domObj = $(element); // The main container DOM element

            this.panels = $("." + this.options.cssprefix + "-panel", this.domObj);
            this.nav = $("." + this.options.cssprefix + "-nav", this.domObj);
            this.navClip = $("." + this.options.cssprefix + "-nav-clip", this.nav);
            this.allItems = this.panels.size();

            // Check if there is any reason to go further
            this.arePanels = this.allItems > 0 ? 1 : 0;
            this.isNavClip = this.navClip.size() > 0 ? 1 : 0;
            if (!this.arePanels && !this.isNavClip) {
                this._errorReport("01", this.options.debug, 1);
            }

            // The function stops if there is no height value (unless 'freeheight' setting is true)
            else if (this.domObj.css("height") == "auto" && !this.options.freeheight) {
                this._errorReport("02", this.options.debug, 1);
            }

            // By default, the widget should be hidden via CSS. Then shown only if javascript is available :
            this.domObj.css("display", "block");

            // Variables that will be needed all over the script			
            this.currId = 0;
            this.prevId = 0;
            this.newId = 0;
            this.currPanel = null;
            this.prevPanel = 0;
            this.firstTime = 1;
            this.scrollActive = 0;
            this.isPlaying = null;
            this.changeOngoing = false;

            // Variables for CSS
            this.cssNames = {
                cssSelected: this.options.cssprefix + "-selected",
                cssActive: this.options.cssprefix + "-panel-active",
                cssOld: this.options.cssprefix + "-panel-old",
                cssBtnDisable: this.options.cssprefix + "-btn-disable",
                cssPanelsWrapper: this.options.cssprefix + "-panels-wrapper",
                cssBtnPause: this.options.cssprefix + "-pause-btn",
                cssPosValue: "+"
            };

            if (this.isNavClip) {
                this._buildNav();
            }

            this._buildControls();

            if (this.arePanels) {
                this.panelsBag = $("." + this.options.cssprefix + "-panels", this.domObj);
                // Panels wrapper : this is only for internal code usage
                // It allows a nice sliding effect in the panels container
                if (this.options.panelfx == "sliding") {
                    this._wrapPanels();
                }
            }

            /*---------------------------------
            *  Navigation settings
            *---------------------------------*/

            // One-click navigation
            if (this.options.panelclick && this.arePanels) {
                this.panelsBag.click(function () {
                    self.stepForward();
                    return false;
                });
            }

            // Slide for the first time
            this.changeWithId(this.options.start >= this.allItems ? this.allItems - 1 : this.options.start < 0 ? 0 : this.options.start, null);

            // Auto-scrolling starter
            if (this.options.auto) {
                this.autoScrollStart();

                // Stops autoScrolling when mouse is over the slider content
                if (!this.isPlayBtn) {
                    this.domObj.hover(
						function () {
						    if (self.isPlaying != null) {
						        self.autoScrollStop();
						    }
						},
						function () {
						    self.autoScrollStart();
						}
					);
                }
            }

            // return this so we can chain/use the bridge with less code.
            return this;
        };

        this._settings = {
            cssprefix: "hslider",
            start: 0,
            auto: true,
            autospeed: 4000,
            mousewheel: false,
            keyboard: false,
            circular: false,
            shownavitems: 5,
            navitemshover: false,
            navclipcenter: false,
            navcontinuous: false,
            navscrollatend: false,
            navpanelautoswitch: true,
            navfx: "sliding",
            scroll: null,
            scrollspeed: 600,
            scrolleasing: null,
            panelfx: "fading",
            panelfxspeed: 700,
            panelfxeasing: null,
            panelfxfirst: "none",
            panelfxbefore: function () { },
            panelfxafter: function () { },
            panelbtnshover: false,
            panelclick: false,
            verticalnav: false,
            verticalslide: false,
            tabs: false,
            freeheight: false,
            fastchange: true,
            debug: false
        };

        this._errorReport = function (errorCode, debug, stop) {
            if (debug) {
                alert("Harold Slider error! Code");
            }
            if (stop) {
                return false;
            }
        };

        this._buildNav = function () {

            this.navUL = $("ul", this.navClip);
            this.navLI = $("li", this.navUL);
            var navLINum = this.navLI.size();

            // Check if nav size is equal to panels size (only if there are panels)
            if (this.arePanels && (navLINum != this.allItems) && this.nav.size() == 1) {
                this._errorReport("03", this.options.debug, 1);
            }

            // If Slider Kit is used as a tabs menu, the nav scroll becomes useless (well, for now...)
            if (this.options.tabs) {
                this.options.shownavitems = this.allItems;
            }

            // Else we start initializing the carousel
            else {
                // LI margins function: returns the <li> tag margins value in pixels
                function getLImargin(attr) {
                    attrVal = self.navLI.css(attr);
                    if (attrVal != "auto" && attr != "" && attr != "0px") {
                        return parseInt(attrVal);
                    }
                    else return 0;
                }

                // Nav elements size
                var navSize = this.options.verticalnav ? this.nav.height() : this.nav.width();
                var navLIWidth = this.navLI.outerWidth(true); // padding + margin + border
                var navLIHeight = this.navLI.outerHeight(true);
                var navLIextHMarg = getLImargin("margin-left") + getLImargin("margin-right");
                var navLIextVMarg = getLImargin("margin-top")/* + getLImargin("margin-bottom")*/;

                this.navLIsize = this.options.verticalnav ? navLIHeight : navLIWidth;
                this.navULSize = this.navLIsize * navLINum;
                this.navClipSize = 830/*(this.options.shownavitems * this.navLIsize)*/ - (this.options.verticalnav ? navLIextVMarg : navLIextHMarg); // Removes the item side margins to center the nav clip

                // CSS attributes for position/height values
                this.cssPosAttr = this.options.verticalnav ? "top" : "left";
                var cssSizeAttr = this.options.verticalnav ? "height" : "width";
                var cssSizeAttrr = this.options.verticalnav ? "width" : "height";

                // Setting height and width values(px) to Clip, UL & LI tags
                this.navLI.css({ width: this.navLI.width(), height: this.navLI.height() });
                this.navUL.css(cssSizeAttr, this.navULSize + "px");
                this.navClip.css({ width: this.options.verticalnav ? navLIWidth : this.navClipSize, height: this.options.verticalnav ? this.navClipSize : navLIHeight });

                // Center the navclip in the nav container
                if (this.options.navclipcenter) {
                    this.navClip.css(this.cssPosAttr, (navSize - this.navClipSize) / 2).css("margin", "0");
                }

                // Check if linescroll is necessary
                this.allItems = navLINum;

                // The nav scrolling is required only if the number of items is greater than the 'visible' param.
                if (this.allItems > this.options.shownavitems) {
                    this.scrollActive = true;

                    // Correcting a potentially 'this.options.scroll' wrong value
                    if (this.options.scroll == null || this.options.scroll < 0 || this.options.scroll > this.allItems) {
                        this.options.scroll = this.options.shownavitems;
                    }

                    // Nav Buttons
                    this.navBtns = $("." + this.options.cssprefix + "-nav-btn", this.nav);
                    if (this.navBtns.size() > 0) {
                        this._buildNavButtons();
                    }
                }
            }

            // Nav <li> links mouse event
            if (this.options.navitemshover && this.arePanels) {
                this.navLI.mouseover(function () {
                    self.changeWithId(getIndex(this, "li"), $(this));
                });
            }
            else if (this.arePanels || this.options.navscrollatend) {
                this.navLI.click(function () {
                    self.changeWithId(getIndex(this, "li"), $(this));
                    return false;
                });
            }

            // Get an item index
            function getIndex(item, tag) {
                return $(tag, $(item).parent()).index(item);
            }

        };

        this._buildNavButtons = function () {

            this.scrollBtns = true;
            this.navBtnPrev = $("." + this.options.cssprefix + "-nav-prev", this.nav);
            this.navBtnNext = $("." + this.options.cssprefix + "-nav-next", this.nav);

            // Nav Buttons click event
            this.navBtnPrev.click(function () {
                self.navPrev();
                return false;
            });
            this.navBtnNext.click(function () {
                self.navNext();
                return false;
            });

            // Nav Buttons mousedown/up events
            if (this.options.navcontinuous) {
                this.navBtnPrev.mouseover(function () {
                    self.navPrev(true);
                });
                this.navBtnNext.mouseover(function () {
                    self.navNext(true);
                });
                this.navBtns.mouseout(function () {
                    self.navStopContinuous();
                });
            }

            // Disable first button if not circular
            if (!this.options.circular) {
                this.navBtnPrev.toggleClass(this.cssNames.cssBtnDisable);
            }

        };

        this._getNavPos = function () {
            this.navPos = this.options.verticalnav ? this.navUL.position().top : this.navUL.position().left;
            this.LIbefore = Math.ceil(Math.abs(this.navPos) / this.navLIsize);
            this.LIafter = Math.floor((this.navULSize - Math.abs(this.navPos) - this.navClipSize) / this.navLIsize);
            if (this.LIafter < 0) {
                this.LIafter = 0;
            }
        };

        this._buildControls = function () {

            this.playBtn = $("." + this.options.cssprefix + "-play-btn", this.domObj);
            this.gBtns = $("." + this.options.cssprefix + "-go-btn", this.domObj);

            this.isPlayBtn = this.playBtn.size() > 0 ? 1 : 0;
            this.goBtns = this.gBtns.size() > 0 ? 1 : 0;

            // Play button
            if (this.isPlayBtn) {

                // If autoscroll is active, the play button is set to 'pause' mode
                if (this.options.auto) {
                    this.playBtn.addClass(this.cssNames.cssBtnPause);
                }

                // Button mouse event
                this.playBtn.click(function () {
                    if (self.playBtn.hasClass(self.cssNames.cssBtnPause)) {
                        self.playBtnPause();
                    }
                    else {
                        self.playBtnStart();
                    }
                    return false;
                });
            }

            // Go buttons (prev/next)
            if (this.goBtns) {
                this.goBtnPrev = $("." + this.options.cssprefix + "-go-prev", this.domObj);
                this.goBtnNext = $("." + this.options.cssprefix + "-go-next", this.domObj);

                // Show/hide buttons on panel mouseover
                if (this.options.panelbtnshover) {
                    this.gBtns.hide();
                    $("." + this.options.cssprefix + "-panels", this.domObj).hover(
						function () {
						    self.gBtns.fadeIn();
						},
						function () {
						    self.gBtns.fadeOut();
						}
					);
                }

                // Button click binding
                this.goBtnPrev.click(function () {
                    self.stepBackward($(this));
                    return false;
                });
                this.goBtnNext.click(function () {
                    self.stepForward($(this));
                    return false;
                });
            }
        };

        this._wrapPanels = function () {
            this.panels.wrapAll('<div class="' + this.cssNames.cssPanelsWrapper + '"></div>');
            this.panelsWrapper = $("." + this.cssNames.cssPanelsWrapper, this.panelsBag);
            this.panelsWrapper.css({ "position": "relative" });
        };

        this._change = function (eventSrc, scrollWay, goToId, lineScrolling, stopAuto) {

            // If there is a play button + auto-scrolling running
            if (stopAuto && this.isPlaying != null && this.isPlayBtn) {
                this.playBtnPause();
            }

            // Don't go further if the side is reached and carousel isn't circular
            // The slide is stopped if the button is disable
            if (eventSrc) {
                if (eventSrc.hasClass(this.cssNames.cssBtnDisable)) {
                    return false;
                }
            }

            // By default, user action is blocked when nav is being animated. This to prevent the function calculation to go mad when the user is switching the items too quickly.
            // This security applies on panels too. However it can be removed using the 'fastchange' option.
            var stopGoing = 0;
            var running = $(":animated", this.options.fastchange ? this.nav : this.domObj).size() > 0 ? 1 : 0;

            if (!running) {
                this.prevId = this.currId;

                // Increment the current id, only if linescrolling isn't required
                if (goToId == null && !lineScrolling) {
                    this.currId = scrollWay == "-=" ? this.currId + 1 : this.currId - 1;
                }
                // Else if an id is given, we take it
                else if (goToId != null) {
                    goToId = parseInt(goToId); // make sure it's a number
                    this.currId = goToId < 0 ? 0 : goToId > this.allItems - 1 ? this.allItems - 1 : goToId; // make sure it's in the nav range
                    var checkIdRange = eventSrc ? eventSrc.parent().parent().hasClass(this.options.cssprefix + "-nav-clip") ? false : true : true;
                }

                // If panel buttons exist, we activate them
                if (this.goBtns) {
                    this.gBtns.removeClass(this.cssNames.cssBtnDisable);
                }

                // If the carousel isn't circular the controls must be hidden when sides are reached
                if (!this.options.circular) {
                    // Top/left side is reached
                    if (this.currId == -1) {
                        this.currId = 0;
                        stopGoing = 1;
                    }
                    if (this.currId == 0 && this.goBtns) {
                        this.goBtnPrev.addClass(this.cssNames.cssBtnDisable);
                    }

                    // Bottom/right side is reached
                    if (this.currId == this.allItems) {
                        this.currId = this.allItems - 1;
                        stopGoing = 1;
                    }

                    if (this.currId == this.allItems - 1) {
                        if (this.options.auto) {
                            this.autoScrollStop();
                        }
                        if (this.goBtns) {
                            this.goBtnNext.addClass(this.cssNames.cssBtnDisable);
                        }
                    }
                }
                // Otherwise if there is no scroll required, this.currId must be reset when sides are reached
                else if (!this.scrollActive) {
                    if (this.currId == this.allItems) {
                        this.currId = 0;
                    }
                    if (this.currId == -1) {
                        this.currId = this.allItems - 1;
                    }
                }

                // If the slide function isn't triggered from a nav LI event, we must check if the line must be scrolled or not
                //if( (goToId == null || this.firstTime) && this.scrollActive && !stopGoing ){
                if (this.scrollActive && !stopGoing) {
                    this._setNavScroll(lineScrolling, scrollWay, checkIdRange);
                }

                // Highlight selected menu
                if (this.isNavClip) {
                    this.selectThumbnail(this.currId);
                }

                // Switch to the next panel
                // Note: if 'navpanelautoswitch' option is false, the panels won't switch when line is scrolling
                if (!(lineScrolling && !this.options.navpanelautoswitch)) {
                    if (this.arePanels) {
                        this._animPanel(this.currId, scrollWay);
                    }
                }

                // First time cancel
                if (this.firstTime) {
                    this.firstTime = 0;
                }

            } // else > be patient, the line scroll is running !
        };

        this._setNavScroll = function (lineScrolling, scrollWay, checkIdRange) {

            // Get the current nav position
            this._getNavPos();

            var triggerLineScroll = lineScrolling ? true : false;
            var jumpToId = 0;

            // No line scrolling required yet : we are going to check the current item position to determine if line scrolling is needed or not.
            if (!lineScrolling) {
                // Line scrolling will happen only if navclip sides are reached
                // Number of items from the clip sides:
                var idFromClipStart = Math.abs(this.currId + 1 - this.LIbefore);
                var idToClipEnd = this.options.shownavitems - idFromClipStart + 1;
                var currIdOnEdge = this.currId == 0 || this.currId == this.allItems - 1 ? 1 : 0;

                // If 'navscrollatend' option is activated, the line will scroll when navclip edges are reached (except if currId is the first or last item of the nav)
                if ((this.options.navscrollatend && (idToClipEnd == 1 || idFromClipStart == 1)) && !this.firstTime && !currIdOnEdge) {
                    jumpToId = this.options.scroll - 1;
                    triggerLineScroll = true;
                }

                // Else the line will scroll when currId is out of the navclip range by -1 or +1
                if (idToClipEnd == 0 || idFromClipStart == 0) {
                    triggerLineScroll = true;
                }

                // A target id is specified (using 'changeWithId' method). No direction ('scrollWay = ""').
                // We check here the difference between target and previous Ids
                if (checkIdRange) {
                    var idDiff = Math.abs(this.prevId - this.currId);

                    // The nav will scroll if the target id is different from the previous Id
                    // The scroll value will then be equal to the 'jumpToId' var, overwriting the 'scroll' option value.
                    if (idDiff > 0) {
                        jumpToId = idDiff;
                        triggerLineScroll = true;
                    }
                }

                // Dertermine scroll direction
                if (scrollWay == "") {
                    if (this.prevId == this.currId && !currIdOnEdge) {
                        scrollWay = this.scrollWay == "-=" ? "+=" : "-=";
                    }
                    else {
                        scrollWay = this.prevId < this.currId ? "-=" : "+=";
                    }
                }
                this.scrollWay = scrollWay;
            }

            // If line scrolling is required
            if (triggerLineScroll) {

                // How many lines will scroll ? By default the answer is 'this.options.scroll' or 'jumpToId'. But we check if there are enough lines left.
                var scrollPower = jumpToId > 0 ? jumpToId : this.options.scroll;
                var LIremain = scrollWay == "-=" ? this.LIafter : this.LIbefore;
                var scrollto = LIremain < scrollPower ? LIremain : scrollPower;
                var scrollSize = scrollto * this.navLIsize;

                // Once the nav has scrolled, the <li> tag matching the currId value may not be visible in the nav clip. So we calculate here a new currId regarding to the nav position.
                this.newId = scrollWay == "-=" ? this.LIbefore + scrollto : this.LIbefore - scrollto + this.options.shownavitems - 1;
                if ((scrollWay == "-=" && this.newId > this.currId) || (scrollWay == "+=" && this.newId < this.currId)) {
                    this.currId = this.newId;
                }

                // Circular option is active
                if (this.options.circular) {
                    if (this.LIbefore <= 0 && scrollWay == "+=") {
                        scrollWay = "-=";
                        this.currId = this.allItems - 1;
                        scrollSize = (this.LIafter / this.options.scroll) * (this.navLIsize * this.options.scroll);
                    }
                    else if (this.LIafter == 0 && scrollWay == "-=") {
                        scrollWay = "+=";
                        this.currId = 0;
                        scrollSize = Math.abs(this.navPos);
                    }
                }

                // Finally, the scroll animation
                this._animNav(scrollWay, scrollSize);
            }
        };

        this._animPanel = function (currId, scrollWay) {

            // Current panel index
            this.currPanel = this.panels.eq(currId);

            // Slide panel (only if not already active)
            if (!this.currPanel.hasClass(this.cssNames.cssActive)) {

                // First panel display (no effect)
                if (this.firstTime) {
                    this.panelTransition = this.options.panelfxfirst;
                    var FirstTime = 1;
                }

                // Else we check for the transition effect
                else {
                    // No effect
                    var freeheightfx = this.options.freeheight && this.options.panelfx == "fading" ? "tabsfading" : "none";
                    this.panelTransition = this.options.freeheight ? freeheightfx : this.options.panelfx;
                }

                // Call the before function is it exists
                if (self.options.panelfxbefore) self.options.panelfxbefore();

                // Call the transition function
                this._panelTransitions[this.panelTransition](scrollWay, FirstTime);
            }
        };

        this._animNav = function (scrollWay, scrollSize) {
            var navComplete = function () {
                // If the nav isn't circular, buttons are disabled when start or end is reached
                if (!self.options.circular && self.scrollBtns) {
                    self.navBtns.removeClass(self.cssNames.cssBtnDisable);

                    // Get the nav position
                    self._getNavPos();

                    if (self.LIbefore <= 0) {
                        self.navBtnPrev.addClass(self.cssNames.cssBtnDisable);
                    }
                    else if (self.LIafter <= 0) {
                        self.navBtnNext.addClass(self.cssNames.cssBtnDisable);
                    }
                }
                // Reload the animation if scrollcontinue option is true
                if (self.scrollcontinue) {
                    setTimeout(function () { self.scrollcontinue == "-=" ? self.navPrev() : self.navNext() }, 0);
                }
            };

            this.navTransition = this.options.navfx;
            this._navTransitions[this.navTransition](scrollWay, scrollSize, navComplete);
        };

        this._panelTransitions = {

            none: function (scrollWay, FirstTime) {
                self.panels.removeClass(self.cssNames.cssActive).hide();
                self.currPanel.addClass(self.cssNames.cssActive).show();
                if (self.options.panelfxafter) { self.options.panelfxafter(); }
            },

            sliding: function (scrollWay, FirstTime) {

                // Slide direction
                if (scrollWay == "") {
                    scrollWay = self.prevPanel < self.currId ? "-=" : "+=";
                }
                self.prevPanel = self.currId;

                // Position/Size values for CSS
                var cssPosValue = scrollWay == "-=" ? "+" : "-";
                var cssSlidePosAttr = self.options.verticalslide ? "top" : "left";
                var domObjSize = self.options.verticalnav ? self.domObj.height() : self.domObj.width();
                var slideScrollValue = cssSlidePosAttr == "top" ? { top: scrollWay + domObjSize} : { left: scrollWay + domObjSize };

                // Panels selection
                self.oldPanel = $("." + self.cssNames.cssOld, self.domObj);
                self.activePanel = $("." + self.cssNames.cssActive, self.domObj);

                // Panels CSS properties
                self.panels.css(cssSlidePosAttr, "0");
                self.oldPanel.removeClass(self.cssNames.cssOld).hide();
                self.activePanel.removeClass(self.cssNames.cssActive).addClass(self.cssNames.cssOld);
                self.currPanel.addClass(self.cssNames.cssActive).css(cssSlidePosAttr, cssPosValue + domObjSize + "px").show();

                // Wrapper animation
                self.panelsWrapper.stop(true, true).css(cssSlidePosAttr, "0").animate(
					slideScrollValue,
					self.options.panelfxspeed,
					self.options.panelfxeasing,
					function () {
					    if (self.options.panelfxafter) self.options.panelfxafter();
					}
				);
            },

            fading: function (scrollWay, FirstTime) {
                if (FirstTime) {
                    self.panels.hide();
                }
                else self.currPanel.css("display", "none");

                $("." + self.cssNames.cssOld, self.domObj).removeClass(self.cssNames.cssOld);
                $("." + self.cssNames.cssActive, self.domObj).stop(true, true).removeClass(self.cssNames.cssActive).addClass(self.cssNames.cssOld);

                self.currPanel.addClass(self.cssNames.cssActive)
				.animate(
					{ "opacity": "show" },
					self.options.panelfxspeed,
					self.options.panelfxeasing,
					function () {
					    if (self.options.panelfxafter) { self.options.panelfxafter(); }
					}
				);
            },

            tabsfading: function (scrollWay, FirstTime) {
                self.panels.removeClass(self.cssNames.cssActive).hide();
                self.currPanel.fadeIn(self.options.panelfxspeed, function () {
                    if (self.options.panelfxafter) { self.options.panelfxafter(); }
                });
            }
        };

        this._navTransitions = {

            none: function (scrollWay, scrollSize, navComplete) {
                var newScrollSize = scrollWay == "-=" ? self.navPos - scrollSize : self.navPos + scrollSize;
                self.navUL.css(self.cssPosAttr, newScrollSize + "px");
                navComplete();
            },

            sliding: function (scrollWay, scrollSize, navComplete) {
                self.navUL.animate(
					self.cssPosAttr == "left" ? { left: scrollWay + scrollSize} : { top: scrollWay + scrollSize }
					, self.options.scrollspeed, self.options.scrolleasing
					, function () {
					    navComplete();
					}
				);
            }
        };

        this.playBtnPause = function () {
            this.playBtn.removeClass(this.cssNames.cssBtnPause);
            this.autoScrollStop();
        };

        this.playBtnStart = function () {
            this.playBtn.addClass(self.cssNames.cssBtnPause);
            this.autoScrollStart();
        };

        this.autoScrollStart = function () {
            var self = this;
            this.isPlaying = setInterval(function () {
                self._change(null, "-=", null, self.lineScrollDo, null);
            }, self.options.autospeed);
        };

        this.autoScrollStop = function () {
            clearTimeout(this.isPlaying);
            this.isPlaying = null;
        };

        this.changeWithId = function (id, eventSrc) {
            this._change(eventSrc, "", id, 0, 1);
        };

        this.stepBackward = function (eventSrc) {
            this._change(eventSrc, "+=", null, self.lineScrollDo, 1);
        };

        this.stepForward = function (eventSrc) {
            this._change(eventSrc, "-=", null, self.lineScrollDo, 1);
        };

        this.navPrev = function (c) {
            if (c) { self.scrollcontinue = "-="; }
            this._change(this.navBtnPrev, "+=", null, 1, 1);
        };

        this.navNext = function (c) {
            if (c) { self.scrollcontinue = "+="; }
            this._change(this.navBtnNext, "-=", null, 1, 1);
        };

        this.navStopContinuous = function () {
            self.scrollcontinue = "";
        };

        this.selectThumbnail = function (currId) {
            $("." + this.cssNames.cssSelected, this.navUL).removeClass(this.cssNames.cssSelected);
            this.navLI.eq(currId).addClass(this.cssNames.cssSelected);
        };

        this.addTransition = function (name, fn) {
            _transitions[name] = fn;
        };
    };

    $.fn.hslider = function (options) {
        // Don't act on absent elements -via Paul Irish's advice
        if (this.length) {
            return this.each(function () {
                // Create a new sliderkit object
                var myHSlider = new hSlider();

                // Run the initialization function of the sliderkit
                myHSlider._init(this, options); // `this` refers to the element

                // Save the instance of the sliderkit object in the element's data store
                $.data(this, "sliderkit", myHSlider);
            });
        }
    };
    $.fn.jsonSuggest = function (settings) {
        var defaults = {
            url: '',
            data: [],
            minCharacters: 1,
            maxResults: undefined,
            wildCard: '',
            caseSensitive: false,
            notCharacter: '!',
            maxHeight: 350,
            highlightMatches: true,
            onSelect: undefined,
            width: 215
        },
			getJSONTimeout;
        settings = $.extend(defaults, settings);

        return this.each(function () {
            /**
            * Escape some text so that it can be used inside a regular expression
            * without implying regular expression rules iself. 
            */
            function regexEscape(txt, omit) {
                var specials = ['/', '.', '*', '+', '?', '|',
								'(', ')', '[', ']', '{', '}', '\\'];

                if (omit) {
                    for (var i = 0; i < specials.length; i++) {
                        if (specials[i] === omit) { specials.splice(i, 1); }
                    }
                }

                var escapePatt = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
                return txt.replace(escapePatt, '\\$1');
            }

            var obj = $(this),
				wildCardPatt = new RegExp(regexEscape(settings.wildCard || ''), 'g'),
				results = $('<ul />'),
				currentSelection, pageX, pageY;

            /**
            * When an item has been selected then update the input box,
            * hide the results again and if set, call the onSelect function.
            */
            function selectResultItem(item) {
                obj.val(item.text);
                $(results).html('').hide();

                if (typeof settings.onSelect === 'function') {
                    settings.onSelect(item);
                }
            }

            /**
            * Used to get rid of the hover class on all result item elements in the
            * current set of results and add it only to the given element. We also
            * need to set the current selection to the given element here.
            */
            function setHoverClass(el) {
                $('li a', results).removeClass('ui-state-hover');
                if (el) {
                    $('a', el).addClass('ui-state-hover');
                }

                currentSelection = el;
            }

            /**
            * Build the results HTML based on an array of objects that matched
            * the search criteria, highlight the matches if that feature is turned 
            * on in the settings.
            */
            function buildResults(resultObjects, filterTxt) {
                filterTxt = '(' + filterTxt + ')';

                var bOddRow = true, i, iFound = 0,
					filterPatt = settings.caseSensitive ? new RegExp(filterTxt, 'g') : new RegExp(filterTxt, 'ig');

                $(results).html('').hide();

                for (i = 0; i < resultObjects.length; i += 1) {
                    var item = $('<li />'),
						text = resultObjects[i].text;

                    if (settings.highlightMatches === true) {
                        text = text.replace(filterPatt, '<strong>$1</strong>');
                    }

                    $(item).append('<a class="ui-corner-all">' + text + '</a>');

                    if (typeof resultObjects[i].image === 'string') {
                        $('>a', item).prepend('<img src="' + resultObjects[i].image + '" />');
                    }

                    if (typeof resultObjects[i].extra === 'string') {
                        $('>a', item).append('<small>' + resultObjects[i].extra + '</small>');
                    }

                    $(item).addClass('ui-menu-item').
						addClass((bOddRow) ? 'odd' : 'even').
						attr('role', 'menuitem').
						click((function (n) {
						    return function () {
						        selectResultItem(resultObjects[n]);
						    };
						})(i)).
						mouseover((function (el) {
						    return function () {
						        setHoverClass(el);
						    };
						})(item));

                    $(results).append(item);

                    bOddRow = !bOddRow;

                    iFound += 1;
                    if (typeof settings.maxResults === 'number' && iFound >= settings.maxResults) {
                        break;
                    }
                }

                if ($('li', results).length > 0) {
                    currentSelection = undefined;
                    $(results).show().css('height', 'auto');

                    if ($(results).height() > settings.maxHeight) {
                        $(results).css({ 'overflow': 'auto', 'height': settings.maxHeight + 'px' });
                    }
                }
            }

            /**
            * Prepare the search data based on the settings for this plugin,
            * run a match against each item in the possible results and display any 
            * results on the page allowing selection by the user.
            */
            function runSuggest(e) {
                var search = function (searchData) {
                    if (this.value.length < settings.minCharacters) {
                        $(results).html('').hide();
                        return false;
                    }

                    var resultObjects = [],
						filterTxt = (!settings.wildCard) ? regexEscape(this.value) : regexEscape(this.value, settings.wildCard).replace(wildCardPatt, '.*'),
						bMatch = true,
						filterPatt, i;

                    if (settings.notCharacter && filterTxt.indexOf(settings.notCharacter) === 0) {
                        filterTxt = filterTxt.substr(settings.notCharacter.length, filterTxt.length);
                        if (filterTxt.length > 0) { bMatch = false; }
                    }
                    filterTxt = filterTxt || '.*';
                    filterTxt = settings.wildCard ? '^' + filterTxt : filterTxt;
                    filterPatt = settings.caseSensitive ? new RegExp(filterTxt) : new RegExp(filterTxt, 'i');

                    // Look for the required match against each single search data item. When the not
                    // character is used we are looking for a false match. 
                    for (i = 0; i < searchData.length; i += 1) {
                        if (filterPatt.test(searchData[i].text) === bMatch) {
                            resultObjects.push(searchData[i]);
                        }
                    }

                    buildResults(resultObjects, filterTxt);
                };

                if (settings.data && settings.data.length) {
                    search.apply(this, [settings.data]);
                }
                else if (settings.url && typeof settings.url === 'string') {
                    var text = this.value;
                    $(results).html('<li class="ui-menu-item ajaxSearching"><a class="ui-corner-all">Searching...</a></li>').
						show().css('height', 'auto');

                    getJSONTimeout = window.clearTimeout(getJSONTimeout);
                    getJSONTimeout = window.setTimeout(function () {
                        $.getJSON(settings.url, { search: text }, function (data) {
                            if (data) {
                                buildResults(data, text);
                            }
                            else {
                                $(results).html('').hide();
                            }
                        });
                    }, 500);
                }
            }

            /**
            * To call specific actions based on the keys pressed in the input
            * box. Special keys are up, down and return. All other keys
            * act as normal.
            */
            function keyListener(e) {
                switch (e.keyCode) {
                    case 13: // return key
                        $(currentSelection).trigger('click');
                        return false;
                    case 40: // down key
                        if (typeof currentSelection === 'undefined') {
                            currentSelection = $('li:first', results).get(0);
                        }
                        else {
                            currentSelection = $(currentSelection).next().get(0);
                        }

                        setHoverClass(currentSelection);
                        if (currentSelection) {
                            $(results).scrollTop(currentSelection.offsetTop);
                        }

                        return false;
                    case 38: // up key
                        if (typeof currentSelection === 'undefined') {
                            currentSelection = $('li:last', results).get(0);
                        }
                        else {
                            currentSelection = $(currentSelection).prev().get(0);
                        }

                        setHoverClass(currentSelection);
                        if (currentSelection) {
                            $(results).scrollTop(currentSelection.offsetTop);
                        }

                        return false;
                    default:
                        runSuggest.apply(this, [e]);
                }
            }

            // Prepare the input box to show suggest results by adding in the events
            // that will initiate the search and placing the element on the page
            // that will show the results.
            $(results).addClass('jsonSuggest ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all').
				attr('role', 'listbox').
				css({
				    'top': (obj.position().top + obj.outerHeight() + 10) + 'px',
				    'left': obj.position().left + 'px',
				    'width': settings.width || (obj.outerWidth() + 'px'),
				    'z-index': 10000
				}).hide();

            obj.after(results).
				keyup(keyListener).
				keydown(function (e) {
				    // for tab key only
				    if (e.keyCode === 9 && currentSelection) {
				        $(currentSelection).trigger('click');
				        return true;
				    }
				}).
				blur(function (e) {
				    // We need to make sure we don't hide the result set
				    // if the input blur event is called because of clicking on
				    // a result item.
				    var resPos = $(results).offset();
				    resPos.bottom = resPos.top + $(results).height();
				    resPos.right = resPos.left + $(results).width();

				    if (pageY < resPos.top || pageY > resPos.bottom || pageX < resPos.left || pageX > resPos.right) {
				        $(results).hide();
				    }
				}).
				focus(function (e) {
				    $(results).css({
				        'top': (obj.position().top + obj.outerHeight() + 10) + 'px',
				        'left': obj.position().left + 'px'
				    });

				    if ($('li', results).length > 0) {
				        $(results).show();
				    }
				}).
				attr('autocomplete', 'off');
            $(window).mousemove(function (e) {
                pageX = e.pageX;
                pageY = e.pageY;
            });

            // Escape the not character if present so that it doesn't act in the regular expression
            settings.notCharacter = regexEscape(settings.notCharacter || '');

            // Make sure the JSON data is a JavaScript object if given as a string.
            if (settings.data && typeof settings.data === 'string') {
                settings.data = $.parseJSON(settings.data);
            }
        });
    };
    //When page loads...
    $('.tab-content').hide(); //Hide all content
    $('ul.tabs li:first').addClass('active').show(); //Activate first tab
    $('.tab-content:first').show(); //Show first tab content	
    //On Click Event
    $("ul.tabs li").click(function () {
      
        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab-content").hide(); //Hide all tab content
        var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active ID content
        return false;
    });
    //When page loads...
    $(".movie-content").hide(); //Hide all content
    $("ul.movie-categories-list li:first").addClass("active").show(); //Activate first tab
    $(".movie-content:first").show(); //Show first tab content	

    //    //Modification Load Data Via AJAX
    //    $.ajax({
    //        url: "/Viewmore/GetList",
    //        data: "TypeID=" + $('ul.movie-categories-list').attr('typeid') + "&GenreID=" + 0,
    //        type: "POST",
    //        success: function (data) {
    //            $('#ResultList').html(data);
    //        }
    //    });

    if ($("ul.movie-categories-list li:first").attr('genre') != null) {
        //Modification Load Data Via AJAX for Category Page
        $.ajax({
            url: "/Viewmore/GetList",
            data: "TypeID=" + $('ul.movie-categories-list').attr('typeid') + "&GenreID=" + null,
            type: "POST",
            success: function (data) {
                $('#ResultList').html(data);
                initPagination();
                hideHoverState();
            }
        });
    } else {
        //Modification Load Data Via AJAX for Channel Page
        if ($('ul.movie-categories-list').attr('typeid') != 3) {
            $.ajax({
                url: "/Viewmore/GetProgramList",
                data: "TypeID=" + $('ul.movie-categories-list').attr('typeid') + "&Origin=" + $("ul.movie-categories-list li:first").attr('orgin') + "&GroupID=" + $("ul.movie-categories-list li:first").attr('groupid'),
                type: "GET",
                success: function (data) {
                    $('#ResultList').html(data);
                    initPagination();
                    hideHoverState();
                }
            });
        }
    }



    //On Click Event
    $("ul.movie-categories-list li").click(function () {
        $("ul.movie-categories-list li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        //$(".movie-content").hide(); //Hide all tab content
        //var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
        //$(activeTab).fadeIn(); //Fade in the active ID content
        //alert("name: " + $(this).attr('name'));

        //display name
        $('div #title_header').html('<h2>' + $(this).attr('name') + '</h2>');

        if ($(this).attr('genre') != null) {
            //Modification Load Data Via AJAX for Category Page
            $.ajax({
                url: "/Viewmore/GetList",
                data: "TypeID=" + $('ul.movie-categories-list').attr('typeid') + "&GenreID=" + $(this).attr('name'),
                type: "POST",
                success: function (data) {
                    $('#ResultList').html(data);
                    initPagination();
                    hideHoverState();
                }
            });
        } else {
            //Modification Load Data Via AJAX for Channel Page

            if ($('ul.movie-categories-list').attr('typeid') != 3) {
                //For VOD and Movie
                $.ajax({
                    url: "/Viewmore/GetProgramList",
                    data: "TypeID=" + $('ul.movie-categories-list').attr('typeid') + "&Origin=" + $(this).attr('orgin') + "&GroupID=" + $(this).attr('groupid'),
                    type: "POST",
                    success: function (data) {
                        $('#ResultList').html(data);
                        initPagination();
                        hideHoverState();
                    }
                });
            } else {
                //For Live Channel
                $.ajax({
                    url: "/Home/GetChannelLiveList",
                    data: "groupid=" + $('ul.movie-categories-list li.active').attr('groupid') + "&day=" + $('li.selected-day').attr('name'),
                    type: "POST",
                    success: function (data) {
                        $('.sched-container').html(data);
                        hideHoverState();
                        altRows();
                    }
                });
            }
        }

        return false;
    });





    $('.panel').css({
        'height': '0px!important',
        'border': 'none',
        'margin': '0!important',
        'padding': '0'
    });
    $('.hcarousel').hslider({
        auto: false,
        scroll: 1,
        mousewheel: true,
        circular: false,
        start: 0
    });
});
