/*---------------------------------------------------------/
|	> Live Chat
+---------------------------------------------------------*/
/**
 * Open a Live Chat po-up window
 *
 * @param string 	url
 */
function startLiveChat(url)
{
	window.open(url, "rf_live_chat", "status=no,titlebar=no,toolbar=no,location=no,menubar=no,resizeable=no,scrollbars=no,screenX=50,screenY=100,width=455,height=370");
}

function initializeChat()
{
	$("#initiate_chat_image").dialog({
		dialogClass: 'rfChatPopUp borderless transparent',
		draggable: false,
		resizable: false,
		width: '430px',
		position: [100, 'center']
	});

	$('.rfChatPopUp div.ui-dialog').removeClass("ui-widget-content");
	$('.rfChatPopUp div.ui-dialog-titlebar').hide();
	$("#initiate_chat_image").removeClass("ui-widget-content");
}

function desposeChat()
{
	$("#initiate_chat_image").dialog( "destroy" );
}

/*---------------------------------------------------------/
|	> Cookies
+---------------------------------------------------------*/
function isCookieEnable()
{
	createCookie('rfTestCookie', 'test', 1);
	
	// if getCookie succeeds, cookies are enabled, since the cookie was successfully created.
	testCookie = readCookie('rfTestCookie');
	
	if(!(testCookie == null || testCookie == ""))
	{
		eraseCookie('rfTestCookie');
		
		return true;
	}
	// if the getCookie test fails, cookies are not enabled for this session.
	else
	{
		return false;
	}
}

function createCookie(name, value, expiry)
{
	$.cookie(name, value, { expires: expiry, path: '/' });
}

function readCookie(name)
{
	return $.cookie(name);
}

function eraseCookie(name)
{
	$.cookie(name, null);
}

/*---------------------------------------------------------/
|	> Cookies >> Chat PoUp
+---------------------------------------------------------*/
function checkVisitLength()
{
	// only pop the chat if the cookie is enable 
	if(isCookieEnable() == true)
	{
		var TimezoneOffset = -7;
		var localTime = new Date();
		var milliseconds = localTime.getTime() + (localTime.getTimezoneOffset() * 60000) + TimezoneOffset * 3600000;

		var pstTime = new Date(milliseconds);
		var day = pstTime.getDay();
		var hour = pstTime.getHours();

		// Sales hours:
		// Monday to Friday 8:00am to 4:00pm
		if( day > 0 && day < 6) // if Monday to Friday
		{
			if( hour >= 8 && hour <= 15)
			{
				var rfVisitTime = readCookie('rfVisitTime');
				
				// existing visitor
				if(rfVisitTime != null)
				{
					var rfChatPopped = readCookie('rfChatPopped');
					
					// see if a chat pop up is ever popped
					if(rfChatPopped == null || rfChatPopped == "")
					{
						trackLengthOfStay();
					}
				}
				else
				{
					// new visitor - start counter
					var now = new Date();
					var expiry = new Date();
					expiry.setHours(expiry.getHours()+12);
					createCookie('rfVisitTime', now, expiry);
					
					setTimeout(checkVisitLength, 1000);
				}
			}
		}
	}
}

function trackLengthOfStay()
{
	rfVisitTime = readCookie('rfVisitTime');
	
	// existing visitor
	if(!(rfVisitTime == null || rfVisitTime == ""))
	{
		var now = new Date();
		now_in_ms = now.getTime();
		rfVisitTime_in_ms = Date.parse(rfVisitTime);

		// if the visitor is staying more than 30 seconds...
		diff_in_ms = now_in_ms - rfVisitTime_in_ms;
		if(diff_in_ms > 60000)
		{
			var expiry = new Date();
			expiry.setHours(expiry.getHours()+12);
			createCookie('rfChatPopped', 1, expiry);

			// pop the chat window
			initializeChat();
		}
	}
	else
	{
		// new visitor
		checkVisitLength();
	}
	
	// self loop until the chat window is popped
	rfChatPopped = readCookie('rfChatPopped');
	if(rfChatPopped == null || rfChatPopped == "")
	{
		setTimeout(trackLengthOfStay, 1000);
	}
}

/*---------------------------------------------------------/
|	> Form Entry Validation
+---------------------------------------------------------*/
function validateEmail(field)
{
	// valid email input -> xxx@yyy.zzz
	var emailFilter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

	if(field.value == '' || field.value == null || !emailFilter.test(field.value))
	{
		return false;
	}

	return true;
}

/*---------------------------------------------------------/
|	> Javascript PHP Equivalent (Credits: http://phpjs.org)
+---------------------------------------------------------*/
/**
 * Checks if a key exists in an array
 *
 * @param string 	key needle
 * @param array		haystack
 */
function array_key_exists (key, search) 
{
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Felix Geisendoerfer (http://www.debuggable.com/felix)
    // *     example 1: array_key_exists('kevin', {'kevin': 'van Zonneveld'});
    // *     returns 1: true
    // input sanitation
    if (!search || (search.constructor !== Array && search.constructor !== Object)) {
        return false;
    }

    return key in search;
}
	
/**
 * Checks if a value exists in an array	
 *
 * @param string         needle
 * @param array          haystack
 * @param boolean		 argStrict
 */
function in_array (needle, haystack, argStrict) 
{
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '',
        strict = !! argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

/**
 * Replaces all occurrences of search in haystack with replace
 *
 * @param string		search
 * @param string		replace
 * @param string		subject
 * @param integer		count
 **/
function str_replace (search, replace, subject, count) 
{
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
    var i = 0,
        j = 0,
        temp = '',
        repl = '',
        sl = 0,
        fl = 0,
        f = [].concat(search),
        r = [].concat(replace),
        s = subject,
        ra = Object.prototype.toString.call(r) === '[object Array]',
        sa = Object.prototype.toString.call(s) === '[object Array]';
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i = 0, sl = s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j = 0, fl = f.length; j < fl; j++) {
            temp = s[i] + '';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length - s[i].length) / f[j].length;
            }
        }
    }
    return sa ? s : s[0];
}
