var ie;
var ns6;

function $(id) {
	var element = false;
	if (id) {
		if (document.getElementById) {
			element = document.getElementById(id);
		} else if (document.all) {
			element = document.all(id);
		}
    }

	return element;
}

function checkNoScript() {
	var elem = $('mainContent');
	if (elem) {
		elem.style.visibility = 'visible';
	}
}


function GWO_trackPageview(str) {
	try {
		_gaq.push(['_trackPageview', '/GWOTRACK/' + str]);
	} catch (err) {}
}

function trackVirtualPage(page_id) {
	try {
		_gaq.push(['_trackPageview', '/virtual/' + page_id]);
//		alert(page_id);
	} catch (err) {}
}

function trackSellerVirtual() {
	trackVirtualPage('enterSlrLogin/' + encodeURIComponent(jQuery(this).text()));
}


/**
 * @todo Do we need ns6 and ie?
 */
function init() {
	if (document.getElementById && !document.all) {
		ns6 = true;
	} else {
		ie = true;
	}
	checkNoScript();
	if (typeof jQuery !== 'undefined') {
		jQuery('a[href$="seller/"]').each(function () {
			this.onclick = trackSellerVirtual;
		});
	}
}


/**
 * Returns true if value only contains spaces
 */
function isBlank(val) {
	var i;
	if (val === null || val.length === 0) {
		return true;
	}
	for (i = 0; i < val.length; i++) {
		if ((val.charAt(i) !== ' ') && (val.charAt(i) !== "\t") && (val.charAt(i) !== "\n") && (val.charAt(i) !== "\r")) {
			return false;
		}
	}
	return true;
}

/**
 * Returns true if value is a 1-character digit (used by isInteger)
 */
function isDigit(num) {
	var string;

	if (num.length > 1) {
		return false;
	}
	string = "1234567890";
	if (string.indexOf(num) !== -1) {
		return true;
	}
	return false;
}

/**
 * Returns true if value contains all digits
 */
function isInteger(val) {
	var i;
	if (isBlank(val)) {
		return false;
	}
	for (i = 0; i < val.length; i++) {
		if (!isDigit(val.charAt(i))) {
			return false;
		}
	}
	return true;
}



/**
 * Returns true if value contains a positive float value
 */
function isNumeric(val) {
	return (parseFloat(val, 10) === (val * 1));
}


//......




function showElement(obj, mode) {


	var elem = typeof obj === "string" ? $(obj) : obj;

	if (elem) {
		if (!mode) {
			if (elem.style.display === "none") {
				elem.style.display = "";
			} else {
				elem.style.display = "none";
			}
		} else {
			if (mode == 1) {
				elem.style.display = "";
			} else {
				elem.style.display = "none";
			}
		}
	}
}


function reverseValue(id) {

	//alert(id);
	var elem = $(id);
	if (elem) {
		if (elem.value === 0) {
			elem.value = 1;
		} else {
			elem.value = 0;
		}
	}
}




function trace(str, flag) {

	var disp = $('disp');
	if (disp) {
		if (!flag) {
			disp.innerHTML = disp.innerHTML + "\n " + str;
		} else {
			disp.innerHTML = str;
		}
	} else {
		alert(str);
	}

}


function goToUrl(url, blank) {
	if (blank) {
		window.open(url);
	} else {
		window.location.href = url;
	}

}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload !== 'function') {
		window.onload = func;
	} else {
		window.onload = function () {
			if (oldonload) {
				oldonload();
			}
			func();
		};
	}
//alert(func);
}


/*****************************
**   Elements class methods
******************************/


function matchClass(objNode, strCurrClass) {
	return (objNode && objNode.className.length && objNode.className.match(new RegExp('(^|\\s+)(' + strCurrClass + ')($|\\s+)')));
}

function getElementsByClassName(objParentNode, strNodeName, strClassName) {
	var nodes, nodesWithClassName, i;

	nodes = objParentNode.getElementsByTagName(strNodeName);
	nodesWithClassName = [];

	if (!strClassName) {
		return nodes;
	}
	for (i = 0; i < nodes.length; i++) {
		if (matchClass(nodes[i], strClassName)) {
			nodesWithClassName[nodesWithClassName.length] = nodes[i];
		}
	}
	return nodesWithClassName;
}



/*****************************
**   AJAX
******************************/


function ajaxLoadHandler(ajaxObject, ajaxCallBackFunction, callObject, params, ajaxCallBackErrorFunction) {
	// only if req shows "complete"
	if (ajaxObject.readyState === 4) {
		// only if "OK"
		if (ajaxObject.status === 200) {
			// ...processing statements go here...
			ajaxCallBackFunction.call(callObject, ajaxObject, params);
		} else {
			if (ajaxCallBackErrorFunction) {
				ajaxCallBackErrorFunction.call(callObject, ajaxObject);
			} else {
				alert("There was a problem retrieving the XML data:\n" + ajaxObject.statusText);
			}
		}
	}
}

function ajaxLoad(url, ajaxCallBackFunction, callObject, params, ajaxCallBackErrorFunction) {
	var ajaxObject = null;

	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest) {
		ajaxObject = new XMLHttpRequest();
		ajaxObject.onreadystatechange = function () {
			ajaxLoadHandler(ajaxObject, ajaxCallBackFunction, callObject, params, ajaxCallBackErrorFunction);
		};
		ajaxObject.open("GET", url, true);
		ajaxObject.send(null);
	// branch for IE/Windows ActiveX version
	} else if (window.ActiveXObject) {
		ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
		if (ajaxObject) {
			ajaxObject.onreadystatechange = function () {
				ajaxLoadHandler(ajaxObject, ajaxCallBackFunction, callObject, params, ajaxCallBackErrorFunction);
			};
			ajaxObject.open("GET", url, true);
			ajaxObject.send();
		}
	}
}



function ajaxLoadPost(url, data, ajaxCallBackFunction, callObject, params, ajaxCallBackErrorFunction) {
	var ajaxObject = null;

	if (window.XMLHttpRequest) { // branch for native XMLHttpRequest object
		ajaxObject = new XMLHttpRequest();
	} else if (window.ActiveXObject) { // branch for IE/Windows ActiveX version
		ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (ajaxObject) {
		ajaxObject.onreadystatechange = function () {
			ajaxLoadHandler(ajaxObject, ajaxCallBackFunction, callObject, params, ajaxCallBackErrorFunction);
		};
		ajaxObject.open("POST", url, true);
		ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
		ajaxObject.setRequestHeader("Content-length", data.length);
		ajaxObject.setRequestHeader("Connection", "close");
		ajaxObject.send(data);
	}
}

function preparePostAJAX(obj) {
	var data, prop;

	data = "";

	for (prop in obj) {
		if (obj.hasOwnProperty(prop)) {
			data += prop + "=" + obj[prop] + "&";
		}
	}
	return data;
}

function handleJson(json) {
	var obj = {};
	try {
		obj = eval("(" + json + ")");
	} catch (e) {
	//alert(json + '\n' + e);
	}
	return obj;
}

function processAJAX(ajaxObject) {
	//alert (ajaxObject.responseText);
	return handleJson(ajaxObject.responseText);
}


//............


function collectValues(ids) {
	var obj, i;

	obj = {};

	for (i = 0; i < ids.length; i++) {
		if ($(ids[i])) {
			obj[ids[i]] = $(ids[i]).value;
		}
	}
	return obj;
}

function sendSafeForm(action, inputs, values, get) {
	var tmp_inp, form, i, str;

	tmp_inp = [];

	form = document.createElement("form");
	form.action = action;
	form.method = get ? 'get' : 'post';

	if (inputs) {
		for (i = 0; i < inputs.length; i++) {
			tmp_inp[i] = document.createElement("input");
			tmp_inp[i].name = inputs[i];
			if ($(inputs[i])) {
				tmp_inp[i].value = $(inputs[i]).value;
				form.appendChild(tmp_inp[i]);
			}
		}
	} else if (values) {
		for (str in values) {
			if (values.hasOwnProperty(str)) {
				tmp_inp[i] = document.createElement("input");
				tmp_inp[i].name =  str;
				tmp_inp[i].value = values[str];
				form.appendChild(tmp_inp[i]);
			}
		}
	}


	document.body.appendChild(form);
	form.submit();
	document.body.removeChild(form);

}

//...........jQuery

var standard_dialog = {
	width : 400,
	modal : true,
	resizable : false,
	title : '',
	zIndex : 8999,
	draggable : false
};

var dialog_initiated = false;

function show_dialog(id, params) {
	var id = "#" + id, str, pos, d;
	if (!dialog_initiated){
		d = standard_dialog;

		if (params) {
			for (str in params) {
				if (params.hasOwnProperty(str)) {
					d[str] = params[str];
				}
			}
		}
		
		jQuery(id).dialog(d);
		dialog_initiated = true;
	}
	else {
		jQuery(id).dialog('open');
	}
	//.......fix mozilla bug scrolling to page top
	if (params && params.force_position) {
		pos = jQuery(".ui-dialog").position();
		window.scrollTo(pos.left, pos.top - 200);
	}
}



function makeExpandableAccordion(id, close_first) {

	id = "#" + id;

	//span class="ui-icon ui-icon-triangle-1-s"/&gt;
//		.prepend('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="ui-icon ui-icon-triangle-1-s"/>')

	jQuery(id).addClass("ui-accordion ui-accordion-icons ui-widget ui-helper-reset")
		.find("h3")
		.addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-top ui-corner-bottom")
		.prepend('<span class="ui-icon ui-icon-triangle-1-s"></span>')
		.hover(function () {
			jQuery(this).toggleClass("ui-state-hover");
		})
		//.prepend('<span class="ui-icon ui-icon-triangle-1-e"></span>')
		.click(function () {
			jQuery(this)
				.toggleClass("ui-accordion-header-active ui-state-active ui-state-default ui-corner-bottom")
				.find("> .ui-icon").toggleClass("ui-icon-triangle-1-e ui-icon-triangle-1-s").end()
				.next().toggleClass("ui-accordion-content-active").slideToggle();
				
			return false;
		})
		.next()
		.addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom")
		.show().hide();
	
	if(!close_first){
		jQuery(id + " > h3:first").find(".ui-icon:first").toggleClass("ui-icon-triangle-1-s ui-icon-triangle-1-e");
		jQuery(id + " > div:first").show();
	}
}


//.............................



var clickTracks = null;

function clickTrack() {
	var val = clickTracks[jQuery(this).attr('id')];
	//alert(window.location.pathname + ' '  + val);
	try {
		_gaq.push(['_trackEvent', window.location.pathname, val, 'Click']);
	} catch (err) {}	
}

function addClickTrack(ids) {
	
	clickTracks = ids;

	jQuery(document).ready(function () {
		var str;
		for (str in clickTracks) {
			if (clickTracks.hasOwnProperty(str)) {
				jQuery("#" + str).bind('click', clickTrack);
			}
		}
	});

}


//...........................

function setCookie(c_name, value, expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + "=" + escape(value) + ((expiredays === null) ? "" : ";expires=" + exdate.toUTCString());
}


function commonSearch() {
	jQuery('#searchForm').submit();
}

function openLearnHow() {
	alert("under development");
}

function print_r(obj) {
	var s = '', str;
	for (str in obj) {
		if (obj.hasOwnProperty(str)) {
			s += str + ' (' + typeof obj[str] + ') = ' + obj[str] + '\n';
		}
		
	}
	return s;
}

addLoadEvent(init);

/*
 * kjs
 */

function acdToggleInlineText(a_Id) {
	var oEl = jQuery('#INLT' + a_Id);
		
	if (oEl.css('display') === 'block') {
		oEl.css('display', 'none');
	} else {
		oEl.css('display', 'block');
	}
		
}

// DM section

// @var debug
window.debug = true;

/**
 * 	Shows or hides element by it's ID
 */
function switchElement(element_id, pause) {
	
	pause = typeof(pause) != 'undefined' ? pause : 0;
	
	if ( true == jQuery( "#" + element_id ).is(':hidden') ) {
		jQuery( "#" + element_id ).show(pause);
	} else {
		jQuery( "#" + element_id ).hide(pause);
	}
}

/**
 * 	Opening wait dialog
 */
function open_wait() {
	
	jQuery('#wait').dialog("destroy");
	
	jQuery('#wait').dialog({
		autoOpen: true,
		resizable: false,
		draggable: false,
		modal: true,
		width: 100,
		height: 100
	});
	
	jQuery('.ui-dialog-titlebar', jQuery('#wait').parent()).remove();
	
	jQuery('#wait').dialog("open");
	
	jQuery('*').bind('close_wait', function(){
		close_wait();
	});
	
}

/**
 * 	closing wait dialog
 * 
 * 	also we can trigger closing:
 * 		jQuery('body').trigger('close_wait');
 */
function close_wait() {
	jQuery('#wait').dialog("destroy");
}

/**
 * 	flash message
 */
function flash_message(message, url, pause) {

	pause = typeof(pause) != 'undefined' ? pause : 5000; // five seconds showing flash message
	url = (typeof(url) != 'undefined' && typeof(url) != null) ? url : null;
	message = typeof(message) != 'undefined' ? message : 'Operation successfully.';
	
	/*if ( url ) {
		message += '<br />You will be redirected now.';
	}*/
	
	jQuery("#flash_message #message").html(message);
	jQuery('#flash_message').fadeIn(500);
	top.window.location.href = '#flash_message'; 
	
	if ( !url ) {
		window.setTimeout("flash_message_hide();", pause);
	} else {
		window.setTimeout("flash_message_hide('"+url+"');", pause);
	}
	
}
function flash_message_hide(url) {
	jQuery('#flash_message').fadeOut(500);
	jQuery('#flash_message').trigger('flash_message_hided');
	//console.log(url);
	if ( url ) {
		top.window.location.href = url;
	}
}

/**
 * 	creating application object
 */
if ( ! top.window.app ) {
	top.window.app = {};
	top.window.app.register_dialog_html = null;
	top.window.app.login_dialog_html = null;
}

function getDialogFromCache(type) {
	switch(type) {
		case 'register':
			if ( top.window.app.register_dialog_html && top.window.app.register_dialog_html !== null ) {
				jQuery('body').append(top.window.app.register_dialog_html);
				return true;
			}
			break;
			
		case 'login':
			if ( top.window.app.login_dialog_html && top.window.app.login_dialog_html !== null ) {
				jQuery('body').append(top.window.app.login_dialog_html);
				return true;
			}
			break;
	}
	
	return false;
}

function saveDialogToCache(type, html) {
	switch(type) {
		case 'register':
			top.window.app.register_dialog_html = html;
			break;
			
		case 'login':
			top.window.app.login_dialog_html = html;
			break;
	}
}

function isEmpty(ob){
   for(var i in ob){ return false;}
  return true;
}

/**
 * 	getting login or register form
 * 
 * 	Examples:
 * 
 * 	getLoginPopup('register', {slr_id: 'testuser', txtPassword: '111111', txtPassword2: '111111', slr_email: 'asd@asd.sd', slr_fname: 'John', slr_lname: 'Doe', cntry_id: 'CA'})
	getLoginPopup('login')
	getLoginPopup('register')
	
	Example with redirection after dialog closed:
		getLoginPopup('login', null, '/my/profile/edit');
 */
function getLoginPopup(type, data, redirect_url) {
	
	jQuery('#login_register_dialog').remove();
	jQuery('#dialog').remove();
	jQuery("#dialog").dialog( "destroy" );
	
	type = ((typeof(type) != 'undefined') ? type : 'login');
	if (type != 'login' && type != 'register') {
		type = 'login';
	}
	
	data = ((typeof(data) != 'undefined') ? data : {});
	
	redirect_url = ((typeof(redirect_url) != 'undefined') ? redirect_url : null);
	
	// we can work with cache only if data not added
	//console.log(data);
	if ( isEmpty(data) ) {
		var is_cache = false;
		is_cache = getDialogFromCache(type);
		if ( is_cache ) {
			return;
		}
	}
	
	open_wait();
	jQuery.ajax({
		url: '/my/?type=' + type,
		'data': data,
		type: 'POST',
		success: function(response) {
			//alert(response);
			// already authorized with ajax. access_token has beeing sat before
			var obj = null;
			try {
				obj = jQuery.parseJSON(response);
			} catch (e) {}
			if (obj && obj.result) {
				top.window.location.href = '/';
				return;
			}
			
			if (top.window.app.dialog_scripts_loaded == true) {
				close_wait();
				//console.dir(response);
				jQuery('body').append(response);
			} else {
				
				/*jQuery('body').bind('dialog-scripts-loaded', function(){
					close_wait();
					//console.dir(response);
					jQuery('body').append(response);
				});*/
				
				/*jQuery.when(function(){
					jQuery.getScript('/content/js/jquery.validate-extended-1.0.js');
					jQuery.getScript('/content/js/jquery.cookie.js');
				})
				.done(function(){
					close_wait();
 					jQuery('body').append(response);
 					top.window.app.dialog_scripts_loaded = true;
				});*/
				
				jQuery.ajax({
  					url: '/content/js/jquery.script-stack-loading-1.0.js',
  					dataType: "script",
  					success: function(){
  						jQuery('body').bind('scripts-loaded', function(event) {
 							close_wait();
 							jQuery('body').append(response);
 							top.window.app.dialog_scripts_loaded = true;
 						});
  						jQuery().LoadAllScripts([
  							'/content/js/jquery.validate-extended-1.0.js',
  						 	'/content/js/jquery.cookie.js'
  						]);
  					}
				});
			}
			
			// binding redirection on dialog closing
			jQuery('body').bind('popup_closed', function(){
				//alert('popup_closed!');
				if ( null != redirect_url ) {
					top.window.app.redirect_url = redirect_url;
					//alert('redirect_url: ' + redirect_url);
					top.window.app.redirecting_from_popup = true;
					//alert('redirecting to ' + redirect_url);
					top.window.location.href = redirect_url;
					return;
				}
			});
			
			jQuery('#dialog').bind('facebook-enter-used', function(){
				if ( null != redirect_url ) {
					top.window.app.redirect_url = redirect_url;
					top.window.app.redirecting_from_popup = true;
					jQuery.cookie('redirect_url', redirect_url);
					//alert(jQuery.cookie('redirect_url'));
					jQuery('#dialog').trigger('js-cookie-sat');
					return;
				}
			});
			
			if ( isEmpty(data) ) {
				saveDialogToCache(type, response);
			}
		}
	});
}

function refresh()
{
	top.document.location.href = top.document.location.protocol 
								 + "//" 
								 + top.document.location.hostname 
								 + top.document.location.pathname;
}

/**
 * 	Checks if email exists in MX records
 * 
 * 	Example of using:
 * 
 * 		
 * 
var email = 'test@example.com';
checkEmailMX(email, function(event, is_correct){
    console.dir(is_correct);
    if (is_correct) {
        alert('email ' + email + ' exists');
    } else {
    	alert('email ' + email + ' NOT exists');
    }
});
 */
function checkEmailMX(email, _function) {
	
	jQuery('body').unbind('email-mx-status-response');
	jQuery('body').bind('email-mx-status-response', _function);
	
	jQuery.ajax({
		url: '/my/ajax/ajaxemailinmx',
		type: 'post',
		dataType: 'json',
		data: {
			"cslr_email": email
		},
		success: function(j) {
			jQuery('body').trigger('email-mx-status-response', [j.result]);
		}
	});
}

function open_Video_Dialog(id, w, h) {
	jQuery('#' + id).dialog('destroy');
	jQuery('#' + id).dialog({
		autoOpen: true,
		width: w,
		height: h,
		modal: true
	});
	
	jQuery('#' + id).dialog('dialogopen', function(){
		jQuery('#' + id).dialog('option', {width: w, height: h});
	});
}

// end DM section


// --- EOF
