﻿var LoadingImgHtml = "<img alt='loading' src='/images/ajax-loader.gif' />";


/// =========== COOKIEEE HELPER ======================
//Set cookie by default is 20 mins
function setCookie(prefix, name, value, minutes)
{
    if (minutes)
        minutes = 20; //default minutes is 20 mins

    var date = new Date();
    date.setTime(date.getTime() + (minutes * 60 * 1000));
    $.cookie(prefix + 'searchString', value, { expires: date });
}


//Get Cookie
function getCookie(prefix, name)
{
    return $.cookie(prefix + name);
}

//Disable all submit buttons
function disableAllSubmitButtons(disabled)
{
    $('input[type=submit]').attr('disabled', disabled)
}

//Disable Default Button
function disableDefaultButton(replaceFunction)
{
    clearDisableDefaultButton(); //Clear Disable Default Button

    //cannot use live.. if use live - when calling die, it must have the same selector
    $("form input").live("keypress", function (e)
    {
        //$.log('run from DISABLE DEFAULT BUtton');
        return runFunctionOnEnter(e, replaceFunction);
    });
}

//Clear Disable Default Button
function clearDisableDefaultButton()
{
    $("form input").die("keypress"); //make it die first so it won't be twice init
}

//Check key press function and will run the function 
function runFunctionOnEnter(e, callbackFunction)
{
    //$.log('callbackFunction1 : ' + callbackFunction);
    //$.log("which : " + e.which + " : keycode : " + e.keyCode);
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13))
    {
        //$.log("TRUE");
        //$.log('callbackFunction2 : ' + callbackFunction);
        if (callbackFunction)
        {
            //$.log("which : " + e.which + " : keycode : " + e.keyCode);
            callbackFunction();
        }
        return false;
    } else
    {
        return true;
    }
}


//==================== SET DIalog IFRAME
//Require JQUIRY.UI http://elijahmanor.com/webdevdotnet/post/jQuery-UI-Dialog-w-Resizable-iFrame.aspx
function setDialogIFrame()
{
    $('.dialogIframeLink').live("click", function (e)
    {
        e.preventDefault();

        var $this = $(this);
        var horizontalPadding = 30;
        var verticalPadding = 30;
        var width = $this.attr('width') ? parseInt($this.attr('width')) : 800;
        var height = $this.attr('height') ? parseInt($this.attr('height')) : 600;
        var modalStr = $this.attr('modal') ? $this.attr('modal') : "true";
        var title = $this.attr('title') ? $this.attr('title') : '';
        var modal = (modalStr == "true") ? true : false;

        var iframe = $('<iframe class="dialogIframe"  src="' + this.href + '" />');
        iframe.dialog({
            title: 'loading...',
            autoOpen: true,
            width: width,
            height: height,
            modal: modal,
            resizable: true,
            autoResize: true,
            overlay: {
                opacity: 0.5,
                background: "black"
            }
        }).width(width - horizontalPadding).height(height - verticalPadding)
            .load(function ()
            {
                //show dialog when it is open
                //$(iframe).dialog('open');
                $(iframe).dialog("option", 'title', title);
            });
    });
}

//Set IFrame loader,so it will show loader first before it loads
function setIFrameShowLoader()
{
    $('iframe.showLoader').before("<div class='loader'><img src='/images/ajax-loader.gif' class='postbackLoading'/> Loading ...<div>");
    $('iframe.showLoader').load(function ()
    {
        $(this).prev().remove();
    });
}




/// =========== Filter Textbox Common Function ======================
/// It required JQuery.Format plugin 
/// /scripts/js/jQuery/jquery.format.FilterTextBox.js
/// http://examplet.buss.hk/jquery/format.php
function setFilterTextbox(panelID)
{
    if (!$.fn.format) return;
    if (panelID)
        panelID = "#" + panelID + " "; //add # selector;
    else
        panelID = "";


    //float number (4 decimal places)
    $(panelID + ".filterFloat").format({ precision: 4, allow_negative: false, autofix: true });

    $(panelID + ".filterDouble").format({ precision: 2, allow_negative: false, autofix: true });

    //money number (2 decimal places)
    $(panelID + ".filterMoney").format({ precision: 2, allow_negative: false, autofix: true });

    //integer
    $(panelID + ".filterInteger").format({ precision: 0, allow_negative: false, autofix: true });

    $(panelID + ".filterEmail").format({ type: "email", autofix: true });

    $(panelID + ".filterAlphabet").format({ type: "alphabet", autofix: true });

    $(panelID + ".filterPhoneNumber").format({ type: "phone-number", autofix: true });
}

/// ===============SET RATING ===========================
/// use V2.1 for Jquery.UI 1.7 and V3 for Jquery.UI 1.8
///    http://orkans-tmp.22web.net/star_rating/#main-menu=5&demo-tabs=1
///    /scripts/js/jQuery/jquery.ui.stars/jquery.ui.stars.2.1/ui.stars.min.css
///    /scripts/js/jQuery/jquery.ui.stars/jquery.ui.stars.2.1/ui.stars.min.js
function setRating(panelID)
{
    if (!$.fn.stars) return;
    if (panelID)
        panelID = "#" + panelID + " "; //add # selector;
    else
        panelID = "";



    $(panelID + ".ratingDropdownlist").stars(
        {
            cancelShow: false,
            inputType: "select"
        }
    );

    $(panelID + ".ratingRadiolist").stars(
        {
            cancelShow: false
        }
    );

    $(panelID + ".ratingDropdownlistDisabled").stars(
        {
            disabled: true,
            cancelShow: false,
            inputType: "select"
        }
    );


    $(panelID + ".ratingRadiolistDisabled").stars(
        {
            disabled: true,
            cancelShow: false
        }
    );

}

/// ===============SET RATING ===========================
/// Require JQUERY UI
function setDatePicker(panelID)
{
    if (!$.fn.datepicker) return;
    if (panelID)
        panelID = "#" + panelID + " "; //add # selector;
    else
        panelID = "";

    $(panelID + ".datepicker").datepicker({
        showOn: "both",
        buttonImage: "/images/calendar.gif",
        buttonImageOnly: true,
        dateFormat: "dd/mm/yy"
    });
}


/// ============ Toogle ITEM ====
/// Use for loader - to show and hide item
function toggleItem(ctlId1, ctlId2)
{
    if (ctlId1)
        $('#' + ctlId1).toggle();

    if (ctlId2)
        $('#' + ctlId2).toggle();
}

// ============ Color PIcker
// Require scripts/jquery/jColorPicker/jpicker-1.1.5.min.js"
//         scripts/jquery/jColorPicker/jPicker.css"
// http://www.digitalmagicpro.com/jPicker/
function setColorPicker(panelID)
{
    if (!$.fn.jPicker) return;
    if (panelID)
        panelID = "#" + panelID + " "; //add # selector;
    else
        panelID = "";

    var colorpickersetting =
    {
        window: // used to define the position of the popup window only useful in binded mode
                        {
                        effects:
                            {
                                type: 'fade', // effect used to show/hide an expandable picker. Acceptable values "slide", "show", "fade"
                                speed:
                                {
                                    show: 'fast', // duration of "show" effect. Acceptable values are "fast", "slow", or time in ms
                                    hide: 'fast' // duration of "hide" effect. Acceptable value are "fast", "slow", or time in ms
                                }
                            },
                        position:
                            {
                                x: 'screenCenter', // acceptable values "left", "center", "right", "screenCenter", or relative px value
                                y: 'center' // acceptable values "top", "bottom", "center", or relative px value
                            }

                    },
        images:
                        {
                            clientPath: '/scripts/js/jQuery/jquery.ColorPicker/images/' // Path to image files                            
                        }

    };

    //set color picker
    $(panelID + '.colorpickerInput').jPicker(colorpickersetting);
}


// ============== Text Area Counter
// Require /scripts/js/jquery/jqueryTextAreaCounter/jquery.textareaCounter.plugin.js
// http://roy-jin.appspot.com/jsp/textareaCounter.jsp
function setTextAreaCounter(panelID)
{

    if (!$.fn.textareaCount) return;
    if (panelID)
        panelID = "#" + panelID + " "; //add # selector;
    else
        panelID = "";


    $(panelID + '.textareaCounter').each(
        function ()
        {
            var maxSize = $(this).attr('rel');
            //$.log('maxsize : ' + typeof(maxSize));
            if (!maxSize)
                maxSize = "250";
            $(this).textareaCount(
                {
                    'maxCharacterSize': maxSize,
                    'warningNumber': 10,
                    'displayFormat': '#input/#max | #words Words'
                }
            );
        }
    );

}

/// <reference path="jquery/jquery.highlight/jquery.highlight.v3.js" />
function showHighlight(selector, searchString, isSplitSpace)
{
    if (!$.fn.highlight) return;

    if (isSplitSpace)
    {
        $(searchString.split(' ')).each(function ()
        {
            $(selector).highlight(this);
        });
    }
    else
    {
        $(selector).highlight(searchString);
    }

}

//Fix Hash - clean ?
var fixHash = function (hash)
{
    return hash.replace("?", "");
};

//Redirect Location
var redirectLocation = function (url)
{
    if (top && top.frames && top.frames.length > 0)
    {
        top.location = url;
    }
    else
    {
        window.location = url;
    }
}


//set watermark field
var setWatermarkField = function ()
{
    // Clears input fields on Focus
    // Title must match the value to clear.
    $(".watermarkInputField").live("blur", function ()
    {        
        if ($(this).val() == "")
        {
            $(this).val($(this).attr("title"));
        };
    });

    $(".watermarkInputField").live("focus", function ()
    {
        if ($(this).val() == $(this).attr("title"))
        {
            $(this).val("");
        };
    });
}




// page refresh button
function refreshPage(url)
{
    if (url)
    {
        //change the url first
        window.location.href = url;
    }

    window.location.reload(false);
}



// Get time diff
function GetTimeDiff(date1, date2)
{
    dt1 = new Date(date1);
    dt2 = new Date(date2);

    var diff;

    if (dt1 > dt2)
    {
        diff = new Date(dt1 - dt2);
    } else
    {
        diff = new Date(dt2 - dt1);
    }

    return diff;
}


//Set Anchor replace with hash
function setAnchorHrefReplaceWithHash()
{
    $('a.anchorHrefReplaceWithHash').each(function ()
    {
        var $this = $(this);
        var href = $this.attr('href');
        if (href)
        {
            href = href.replace('?', '#'); //replace with hash

            $this.attr('href', href);
        }
    });
}

function setCookie(name,value,expires) {
	document.cookie = name+"="+value+"; path=/";
}

function getCookie(name,value) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i<ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) {
			if (c.substring(nameEQ.length,c.length) == value) {
				//alert("COOKIE CHECK - FOUND");
				return true;
			}
		}
	}
	//alert("COOKIE CHECK - NO COOKIE");
	return false;
}

//setup hide box trigger
var setHideBoxTrigger = function ()
{
	if (getCookie(".shopMessageContainer","closed") == true) {
		$('.shopMessageArea').hide();
	}
	
    $('.hideBoxTrigger').live("click", function (e)
    {
        e.preventDefault();

        // Make the drop down cart appear/disappear.
        var boxSelector = $(this).attr('rel');

        // Set natural height and other properties of hidable object.
        $(boxSelector).hide('fast');
        setCookie(boxSelector,"closed","");
    });
}

//setup show box trigger
var setShowBoxTrigger = function ()
{
    $('.showBoxTrigger').live("click", function (e)
    {
        e.preventDefault();

        // Make the drop down cart appear/disappear.
        var boxSelector = $(this).attr('rel');

        // Set natural height and other properties of hidable object.
        $(boxSelector).show('slow');
    });
}

//setup Dropdown Item
var setDropdownItemTrigger = function (beforeDropDownToggleHandler)
{
    //find drop down item trigger
    $('.dropdownItemTrigger').each(function ()
    {
        // Make the drop down cart appear/disappear.
        var boxSelector = $(this).attr('rel');

        // Set natural height and other properties of hidable object.
        $(boxSelector).data('naturalHeight', $(boxSelector).height());
        $(boxSelector).addClass('hidden');
        $(boxSelector).css(
		    {
		        display: 'none',
		        bottom: 'auto'
		    });

        // Create back reference.
        $(boxSelector).data('trigger', $(this));
    });

    $('.dropdownItemTrigger').live("click", function (e)
    {
        e.preventDefault();

        var $trigger = $(this);

        // Don't do anything if the drop down item is already animating.
        if ($trigger.hasClass('disabled')) return false;

        // Find direction.
        var direction = $trigger.hasClass('maximise') ? 1 : -1;

        // Find effect type.
        var classes = $trigger.attr('class'); //.match(/effect-/);
        var effect = $trigger.attr('class').match(/\beffect-[a-z]{1,}/);
        //alert(effect);

        // Make the drop down cart appear/disappear.
        var boxSelector = $trigger.attr('rel');

        if (beforeDropDownToggleHandler)
        {
            beforeDropDownToggleHandler(boxSelector);
        }

        $(boxSelector).trigger('dropdowntoggle', [direction, effect]);
    });

    $('.dropdownItem').live('dropdowntoggle', function (e, direction, fxtype)
    {
        var $dropdownItem = $(this);
        var $trigger = $dropdownItem.data('trigger');


        // Ensure direction.
        if (isNaN(direction)) direction = $dropdownItem.hasClass('shown') ? -1 : 1;

        // Disable trigger.
        $trigger.addClass('disabled');

        // Set states. / cursor            
        $trigger.toggleClass('maximise', direction == -1);
        $trigger.toggleClass('minimise', direction == 1);

        $dropdownItem.toggleClass('hidden', direction == -1);
        $dropdownItem.toggleClass('shown', direction == 1);

        // Effect 
        //var currPosition = $dropdownItem.css('top').replace(/([a-z]+)/, '') * 1
        var currPosition; // = direction == 1 ? $dropdownItem.height() * -1 : 0;
        var displacement; // = $dropdownItem.height(); //$dropdownItem.data('naturalHeight');
        var newPosition; // = currPosition + displacement * direction;

        //alert(fxtype);
        // Toggle drop down item + Effect
        if (fxtype == 'effect-slide')
        {
            // Calculate new values.
            currPosition = direction == 1 ? ($dropdownItem.height() * -1) : 0 - 50;
            displacement = $dropdownItem.height(); //$dropdownItem.data('naturalHeight');
            newPosition = currPosition + displacement * direction;

            // Execute
            $dropdownItem.css(
						{
						    display: 'block',
						    top: currPosition
						}).animate(
						{
						    top: newPosition
						}, 400, function ()
						{
						    $trigger.toggleClass('active', direction == 1);

						    $trigger.removeClass('disabled');
						});
        }
        else
        {
            // if (fxtype=='effect-fade') {
            // Calculate new values.
            var currOpacity = direction == 1 ? 0 : 1;
            var newOpacity = direction == 1 ? 1 : 0;


            //Execute
            $dropdownItem.css(
						{
						    display: 'block',
						    //top: 0,
						    opacity: currOpacity
						}).animate(
						{
						    opacity: newOpacity
						}, 400, function ()
						{
						    $trigger.toggleClass('active', direction == 1);
						    if (direction == -1)
						    {
						        //hide the display
						        $dropdownItem.css({ display: 'none' });
						    }
						    $trigger.removeClass('disabled');
						});
        }

    });
};

/*this doesn't work for shopping cart in IE 6*/
var setDropdownItemTriggerUsingJqueryUI = function ()
{
    //Bind Drop down item - just require this button
    $('.dropdownItemTriggerBlind').live("click", function (e)
    {
        e.preventDefault();

        var $trigger = $(this);
        // Make the drop down cart appear/disappear.
        var boxSelector = $trigger.attr('rel');

        //check if it is shopping cart control
        if (boxSelector == shoppingCartControl.shoppingCartControlSelector)
        {
            shoppingCartControl.checkToReload();
        }


        //using jquery.ui toggle( effect, [options], [speed], [callback] )
        $(boxSelector).toggle('blind', null, 300);

    });

}


/* removeHideFirstBeforeJSLoading used for product listing */
var removeHideFirstBeforeJSLoading = function ()
{
    //Remove hide first before loading
    $(".hideFirstBeforeJSLoading").removeClass("hideFirstBeforeJSLoading");

}

