//
// $Id: ajax.js 7885 2009-08-21 15:09:58Z zeke $
//

jQuery.extend({
	ajaxRequest: function(url, params)
	{

		params = params || {};
		params.method = params.method || 'get';
		params.callback = params.callback || {};
		params.data = params.data || {};
		params.message = params.message || lang.loading;
		params.caching = params.caching || false;
		params.hidden = params.hidden || false;
		params.low_priority = params.low_priority || false;
		params.force_exec = params.force_exec || false;
		var QUERIES_LIMIT = 1;

		if (jQuery.active_queries >= QUERIES_LIMIT) { // if we have queries in the queue, push request to it
			if (params.low_priority == true) {
				jQuery.queries_stack.push(function() {
					jQuery.ajaxRequest(url, params);
				});
			} else {
				jQuery.queries_stack.unshift(function() {
					jQuery.ajaxRequest(url, params);
				});
			}

			return true;
		}

		if (params.preload_obj && params.caching) {
			if (params.preload_obj.data('is_loaded')) {
				return true;
			}
		}

		// If query is not hidden, display loading box
		if (params.hidden == false) {
			jQuery.toggleStatusBox('show', params.message);
		}

		if (jQuery.ajax_cache[jQuery.last_hash]) {
			for (var id in jQuery.ajax_cache[jQuery.last_hash].data.html) {
				jQuery.ajax_cache[jQuery.last_hash].data.html[id] = $('#' + id).html();
			}
		}

		var hash = '';
		if (params.caching == true) {
			hash = jQuery.crc32(url + jQuery.param(params.data));
			jQuery.last_hash = hash;
		}

		if (!hash || !jQuery.ajax_cache[hash]) {
			url = fn_query_remove(url, 'result_ids');

			// Add result IDs to data
			if (params.result_ids) {
				params.data.result_ids = params.result_ids;
			}

			if (params.caching && params.store_init_content && !jQuery.ajax_cache.init_content) {
				jQuery.ajax_cache.init_content = {};
				if (params.result_ids) {
					jQuery.ajax_cache.init_content.data = {};
					jQuery.ajax_cache.init_content.data.html = {};
					var ids = params.result_ids.split(',');
					for (var k = 0; k < ids.length; k++) {
						elm = $('#' + ids[k]);
						if (elm.length) {
							jQuery.ajax_cache.init_content.data.html[ids[k]] = elm.html();
						}
					}
				}
			}

			if (url) {
				jQuery.active_queries++;
				jQuery.ajax({
					type: params.method,
					url: url,
					dataType: 'json',
					cache: true,
					data: params.data,
					success: function(data, textStatus) {

						if (params.preload_obj) {
							if (params.preload_obj.data('is_loaded') && params.caching) {
								return false;
							}
							params.preload_obj.data('is_loaded', true);
						}

						if (hash) { // cache response
							jQuery.ajax_cache[hash] = data;
						}

						jQuery.ajaxResponse(data, params);
						jQuery.active_queries--;
						if (jQuery.queries_stack.length) {
							var f = jQuery.queries_stack.shift();
							f();
						}
					}
				});
			}

		} else if (hash && jQuery.ajax_cache[hash]) {
			jQuery.ajaxResponse(jQuery.ajax_cache[hash], params);
		}
	},

	ajaxSubmit: function(form, elm)
	{
		var callback = 'fn_form_post_' + form.attr('name');
		var f_callback = window[callback] || null;
		var REQUEST_XML = 1;
		var REQUEST_IFRAME = 2;

		if (form.attr('enctype') == 'multipart/form-data' && form.hasClass('cm-ajax')) {
			if (!$('iframe[name=upload_iframe]').length) {
				$('<iframe name="upload_iframe" src="javascript: false;" class="hidden"></iframe>').appendTo('body');
				$('iframe[name=upload_iframe]').load(function() {
					eval('var response = ' + $(this).contents().find('textarea').val());
					jQuery.ajaxResponse(response, {callback: f_callback});
				});
			}

			form.append('<input type="hidden" name="is_ajax" value="' + REQUEST_IFRAME + '" />');
			form.attr('target', 'upload_iframe');
			jQuery.ajaxRequest('', null);

			return true;
		} else {
			var hash = $(':input', form).serializeArray();

			// Send name/value of clicked button
			hash.push({name: elm.attr('name'), value: elm.val()});

			jQuery.ajaxRequest(form.attr('action'), {
				method: form.attr('method'),
				data: hash,
				callback: f_callback,
				force_exec: form.hasClass('cm-ajax-force') ? true : false
			});

			return false;
		}
	},

	ajaxResponse: function(response, params)
	{
		params = params || {};
		params.force_exec = params.force_exec || false;
		params.callback = params.callback || {};

		var regex_all = new RegExp('<script[^>]*>([\u0001-\uFFFF]*?)</script>', 'img');
		var matches = [];
		var match = '';
		var elm;
		var data = response.data || {};

		if (!jQuery.loaded_scripts) {
			jQuery.loaded_scripts = [];
			$('script').each(function() {
				var _src = $(this).attr('src');
				if (_src) {
					jQuery.loaded_scripts.push(jQuery.getBaseName(_src));
				}
			})
		}

		// Ajax request forces browser to redirect
		if (data.force_redirection) {
			jQuery.redirect(data.force_redirection);
		}

		// Data returned that should be inserted to DOM
		if (data.html) {
			for (var k in data.html) {
				elm = $('#' + k);
				if (elm.length != 1) {
					continue;
				}

				matches = data.html[k].match(regex_all);
				elm.html(matches ? data.html[k].replace(regex_all, '') : data.html[k]);
				
				// Display/hide hidden block wrappers
				if (jQuery.trim(elm.html())) {
					elm.parents('.hidden.cm-hidden-wrapper').removeClass('hidden');
				} else {
					elm.parents('.cm-hidden-wrapper').addClass('hidden');
				}

				// If returned data contains scripts, execute them
				if (matches) {
					for (var i = 0; i < matches.length; i++ ) {
						var m = $(matches[i]);

						// External script
						if (m.attr('src')) {
							var _src = jQuery.getBaseName(m.attr('src'));
							if (jQuery.inArray(_src, jQuery.loaded_scripts) == -1) {
								jQuery.loaded_scripts.push(_src);
								m.appendTo('body');
							}
						} else {
							var _hash = jQuery.crc32(m.html());
							if (!this.eval_cache[_hash] || params.force_exec || m.hasClass('cm-ajax-force')) {
								this.eval_cache[_hash] = true;
								if (window.execScript) {
									window.execScript(m.html());
								} else {
									window.eval(m.html());
								}
							}
						}
					}
				}


				$(".cm-j-tabs", elm).each(function(){ $(this).idTabs(); });

				// if returned data contains forms, process them
				if (data.html[k].indexOf('<form') != -1) {
					jQuery.processForms(elm);
				}
				if (elm.parents('form').length) {
					elm.parents('form:first').highlightFields();
				}

				if (elm.data('callback')) {
					elm.data('callback')();
					elm.removeData('callback');
				}
			}
		}

		// Display notification
		if (data.notifications) {
			jQuery.showNotifications(data.notifications);
		}

		// If callback functio passed, run it
		if (params.callback) {
			if (typeof(params.callback) == 'function') { // call ordinary function
				params.callback(data, params);
			} else if (params.callback[1]) { // call object method [obj, 'meth']
				params.callback[0][params.callback[1]](data, response.text, params);
			}
		}

		// Hide loading box
		jQuery.toggleStatusBox('hide');
	},

	objectSerialize: function (d, suff, l)
	{

		if (l == null) {
			l = 1;
		}
		if (suff == null) {
			suff = '';
		}

		var s = '';

		if (typeof(d) == "object") {
			for (var k in d) {
				var _suff = (l == 1 ? k : suff + "[" + k + "]");
				s += this.objectSerialize(d[k], _suff, l + 1);
			}
		} else {
			s += suff + "=" + d + "&";
		}

		return s;
	},

	getBaseName: function (path)
	{
		return path.split('/').pop();
	},
	
	loadAjaxLinks: function(elms, high_priority)
	{
		elms.each(function() {
			var a = $(this);
			var p = !(high_priority || false);
			if (a.data('is_loaded') || a.parents(':hidden').length) { // do no load hidden links
				return false;
			}

			var _form = a.parents('form');

			var _obj = $('#' + a.attr('id').str_replace('opener_', ''));

			if (_form.length == 1) {
				_form.before(_obj);
			} else {
				$('body').append(_obj);
			}

			var params = {
				caching: true,
				hidden: p,
				result_ids: a.attr('rev'),
				low_priority: p,
				preload_obj: a
			};

			jQuery.ajaxRequest(a.attr('href'), params);
		});
	},

	ajax_cache: {},
	queries_stack: [],
	active_queries: 0,
	eval_cache: {},
	last_hash: ''
});

$(window).load(function(){
	jQuery.loadAjaxLinks($('a.cm-ajax-update'));
});

function fn_query_remove(query, vars)
{
	if (typeof(vars) == 'undefined') {
		return query;
	}
	if (typeof vars == 'string') {
		vars = [vars];
	}
	var start = query;
	if (query.indexOf('?') >= 0) {
		start = query.substr(0, query.indexOf('?'));
		var search = query.substr(query.indexOf('?'));
		var srch_array = search.split("&");
		var temp_array = new Array();
		var concat = true;
		var amp = '';
		for (var i = 0; i < srch_array.length; i++) {
			temp_array = srch_array[i].split("=");
			concat = true;
			for (var j = 0; j < vars.length; j++) {
				if (vars[j] == temp_array[0] || temp_array[0].indexOf(vars[j]+'[') != -1) {
					concat = false;
					break;
				}
			}
			if (concat == true) {
				start += amp + temp_array[0] + '=' + temp_array[1]
			}
			amp = '&';
		}
	}
	return start;
};


/*
Copyright (c) 2009, www.redips.net  All rights reserved.
Code licensed under the BSD License: http://www.redips.net/license/

http://www.redips.net/javascript/dialog-box/
version 1.2.0
Nov 23, 2009.
*/

/*jslint white: true, browser: true, undef: true, nomen: true, eqeqeq: true, plusplus: false, bitwise: true, regexp: true, strict: true, newcap: true, immed: true, maxerr: 14 */
/*global window: false */



/* enable strict mode */
"use strict";

// create REDIPS namespace
var REDIPS = {};



REDIPS.dialog = (function () {
		// function declaration
	var	init,
		show,
		hide,
		position,
		visibility,
		fade,
		
		// private parameters
		shade,				// shade div (object reference)
		dialog_box,			// dialog box (object reference)
		dialog_width = 0,	// initialize dialog width
		dialog_height = 0,	// initialize dialog height
		op_high = 60,		// highest opacity level
		op_low = 0,			// lowest opacity level (should be the same as initial opacity in the CSS)
		fade_speed = 18,	// set default speed - 18ms 
		function_call;		// name of function to call after clicking on button 


	// initialization
	init = function () {
		// create dialog box
		dialog_box = document.createElement('div');
		dialog_box.setAttribute('id', 'dialog');
		// create shade div
		shade = document.createElement('div');
		shade.setAttribute('id', 'shade');
		// append dialog box and shade to the page body
		var body = document.getElementsByTagName('body')[0];
		body.appendChild(shade);
		body.appendChild(dialog_box);
		// define onscroll & onresize event handler for FF, Chrome		
		if (window.addEventListener) {
			window.addEventListener('scroll', position, false);
			window.addEventListener('resize', position, false);
		}
		// IE
		else if (window.attachEvent) {
			window.attachEvent('onscroll', position);
			window.attachEvent('onresize', position);
		}
		// other (hopefully this will not be needed)
		else {
			window.onscroll = position;
			window.onresize = position;
		}
	};
	
	
	// show dialog box
	show = function (width, height, text, button1, button2) {
		var input1 = '',	// define input1 button
			input2 = '',	// define input2 (optional) button
			img,			// needed to find image suffix
			img_text;		// display text under image
		//  set button1 default value
		if (button1 === undefined) {
			button1 = 'Continue';
		}
		// set dialog width, height and calculate central position
		dialog_width  = width;
		dialog_height = height;
		position();
		// if text ends with jpg, jpeg, gif or png, then prepare img tag
		img = /(\.jpg|\.jpeg|\.gif|\.png)$/i;
		if (img.test(text)) {
			// text can precede jpg, jpeg, gif or png image, so search for separator
			img_text = text.split('|');
			// separator doesn't exist, display only image
			if (img_text[1] === undefined) {
				text = '<IMG src="' + img_text[0] + '" height="' + (height - 40) + '"/>';
			}
			// otherwise, display image and text beneath image (text is closed in P tags)
			else {
				text = '<IMG src="' + img_text[1] + '" height="' + (height - 40) + '"/>';
				text += '<P>' + img_text[0] + '</P>';
			}
		}
		// prepare button1
		button1 = button1.split('|');
		input1 = '<span class="button"><a onclick="REDIPS.dialog.hide(\'' + button1[1] + '\');">' + button1[0] + '</a></span>';
		// prepare optional button2 
		if (button2 !== undefined) {
			button2 = button2.split('|');
			input2  = '<INPUT type="button" onclick="REDIPS.dialog.hide(\'' + button2[1] + '\');" value="' + button2[0] + '">';
		}
		// set HTML for dialog box - use table to vertical align content inside
		// dialog box (this should work in all browsers)
		dialog_box.innerHTML = '<TABLE><TR><TD valign="center" height="' + height + 
								 '" width="' + width + '"><P>' + text + '</P><P>' + input1 + input2 + '</P>' +
								 '</TD></TR></TABLE>';
		// show shade and dialog box
		shade.style.display = dialog_box.style.display = 'block';
		// hide dropdown menus, iframes & flash
		visibility('hidden');
		// show shaded div slowly
		fade(op_low, 10);
	};
	
	
	// hide dialog box and shade
	hide = function (fnc) {
		// set function call
		function_call = fnc;
		// start fade out
		fade(op_high, -20);
		// hide dialog box
		dialog_box.style.display = 'none';
		// show dropdown menu, iframe & flash
		visibility('visible');
		
	};
	
	
	// function sets dialog position to the center and maximize shade div
	position = function () {
		// define local variables
		var window_width, window_height, scrollX, scrollY;
		// Non-IE (Netscape compliant)
		if (typeof(window.innerWidth) === 'number') {
			window_width  = window.innerWidth;
			window_height = window.innerHeight;
			scrollX = window.pageXOffset;
			scrollY = window.pageYOffset;
		}
		// IE 6 standards compliant mode
		else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
			window_width  = document.documentElement.clientWidth;
			window_height = document.documentElement.clientHeight;
			scrollX = document.documentElement.scrollLeft;
			scrollY = document.documentElement.scrollTop;
			// IE hack because #shade{width:100%;height:100%;} will not work for IE if body{height:100%} isn't set also ?!
			shade.style.width   = window_width  + 'px';
			shade.style.height  = window_height + 'px';
		}
		// DOM compliant
		else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
			window_width  = document.body.clientWidth;
			window_height = document.body.clientHeight;
			scrollX = document.body.scrollLeft;
			scrollY = document.body.scrollTop;
		}
		// place dialog box to the center
		dialog_box.style.left = (scrollX + ((window_width  - dialog_width)  / 2)) + 'px';
		dialog_box.style.top  = (scrollY + ((window_height - dialog_height) / 2)) + 'px';
		// set shade offset
		shade.style.top  = scrollY + 'px';
		shade.style.left = scrollX + 'px';
	};
	
	
	// show/hide dropdown menu, iframe and flash objects (work-around for dropdown menu problem in IE6)
	visibility = function (p) {
		var obj = [],	// define tag array
			x, y;		// variables used in local loops
		obj[0] = document.getElementsByTagName('select');
		obj[1] = document.getElementsByTagName('iframe');
		obj[2] = document.getElementsByTagName('object');
		// loop through fetched elements
		for (x = 0; x < obj.length; x++) {
			for (y = 0; y < obj[x].length; y++) {
				obj[x][y].style.visibility = p;
			}
		}
	};
	
	
	// shade fade in / fade out
	fade = function (opacity, step) {
		// set opacity for FF and IE
		shade.style.opacity = opacity / 100;
		shade.style.filter  = 'alpha(opacity=' + opacity + ')';
		// update opacity level
		opacity += step;
		// recursive call if opacity is between 'low' and 'high' values
		if (op_low <= opacity && opacity <= op_high) {
			setTimeout(
				function () {
					fade(opacity, step);
				}, fade_speed); // fade speed is public parameter
		}
		// hide shade div when fade out ends and make function call 
		else if (op_low > opacity) {
			shade.style.display = 'none';
			if (function_call !== 'undefined') {
				// call function after button is clicked because functions are defined in global scope
				window[function_call]();
			}
		}
	};
	
	return {
		// public properties
		op_high			: op_high,		// highest opacity level
		op_low			: op_low,		// lowest opacity level (should be the same as initial opacity in the CSS)
		fade_speed		: fade_speed,	// fade speed (default is 18ms)
        
		// public methods
		init			: init,			// initialization
		show			: show,			// show dialog box
		hide			: hide			// hide dialog box
	};
			
}());




//
// onclick button handlers needed for examples in dialog call
//


// execute after button1 is clicked 
function button1() {
	alert('Hi from function button1 ...');
}

// execute after button2 is clicked
function button2() {
	alert('Hi from function button2 ...');
}


// after page is loaded, initialize DIV elements inside tables
//window.onload = function () {
	//REDIPS.dialog.init();
	//REDIPS.dialog.show(120, 100, "<h1>Welcome to mydeskfriend Store</h1> Don't forget to select your localization.");
//};

$(window).load(function(){





	
	
			//try{
						//if($('#idtesting').html()){		
			//if($('#sw_select_3_wrap_').html()){
			//
							//$('#idtesting').html('us');
							//$('#en_taxes').html('');
							//$('#en_shipping').html('Shipping the next day from San Fransisco, CA.');
							//$('#fr_taxes').html('');
							//$('#fr_shipping').html('Envoyé le lendemain depuis San Fransisco, CA.');
							//
					//}else{
//
					//$('#idtesting').html('not us');
					//$('#en_taxes').html('');
					//$('#en_shipping').html('Shipping the next day from Switzerland.');
					//$('#fr_taxes').html('');
					//$('#fr_shipping').html('Envoyé le lendemain depuis la Suisse.');
				//}
			//}
				
				
				
				
				
				
				
				
				
					//if(!Get_Cookie('sess_id')){}
					if(!Get_Cookie('mdf_loc')){
					//alert('start - on load dialogbox! :: ');
								REDIPS.dialog.init();
								//	REDIPS.dialog.show(500, 120, "<h1>Welcome to mydeskfriend Store</h1> Don't forget to select your localization.");
								//REDIPS.dialog.show(500, 120, "COOKIES" + Get_Cookies());
								REDIPS.dialog.show(270, 325, "<h1>Welcome to </h1><br>\
								<img src='http://www.arimaz.com/mydeskfriend/images/product/ad_image.gif'/><br>\
								 <h2>Store</h2><br> Don't forget to select your localization." + "<div class='select-wrap localization'>\
								<br>\
								<!--<div id='errorus'style='color:#990000'>error</div>-->\
								<br>\
								<br>\
								Localization:	\
								<a id='enter_local' class='select-link cm-combo-on cm-combination'>Choose region</a>\
								<div class='select-popup cm-popup-box hidden' id='select_local'>\
									<img height='13' border='0' width='13' class='close-icon no-margin cm-popup-switch' alt='' src='/store/skins/basic/customer/images/icons/icon_close.gif'/>\
									<ul class='cm-select-list'>\
														<li><a class='' href='/store/?lc=4' name='4' rel='nofollow'>Europe</a></li>\
														<li><a class='' href='/store/?lc=2' name='2' rel='nofollow'>International</a></li>\
														<li><a class='active' href='/store/?lc=1' name='1' rel='nofollow'>Switzerland</a></li>\
														<li><a class='' href='/store/?lc=3' name='3' rel='nofollow'>United States</a></li>\
												</ul>\
								</div>\
							<br>\
								<br>\
								<br>\
								</div>");
									
									dialog_box_test = 1;
					Set_Cookie( 'mdf_loc', 'visited', 10, '/', '', '' );
					//	alert('end - on load dialogbox! :: ');
					}
			}catch(e){
				
				alert('error - on load dialogbox! :: '+ e);
				}
});

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}


// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}


// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookies() {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	return a_all_cookies;
	//for ( i = 0; i < a_all_cookies.length; i++ )
	//{
		//// now we'll split apart each name=value pair
		//a_temp_cookie = a_all_cookies[i].split( '=' );


		//// and trim left/right whitespace while we're at it
		//cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		//// if the extracted name matches passed check_name
		//if ( cookie_name == check_name )
		//{
			//b_cookie_found = true;
			//// we need to handle case where cookie has no value but exists (no = sign, that is):
			//if ( a_temp_cookie.length > 1 )
			//{
				//cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			//}
			//// note that in cases where cookie is initialized but no value, null is returned
			//return cookie_value;
			//break;
		//}
		//a_temp_cookie = null;
		//cookie_name = '';
	//}

}

