/**
 * @author Wzi JB
 */
var Wizishop = YAHOO.namespace('Wizishop');
var Wizishop = YAHOO.Wizishop;
Wizishop.Produits = {};

//if (typeof Wizishop == "undefined" || !Wizishop) {
//    /**
//     * The Wizishop global namespace object.  If Wizishop is already defined, the
//     * existing Wizishop object will not be overwritten so that defined
//     * namespaces are preserved.
//     * @class Wizishop
//     * @static
//     */
//    var Wizishop = {};
//}

if (!window.console || !window.console.firebug) {
    window.console = {
        error: function(){
        },
        debug: function(){
        },
        info: function(){
        },
        log: function(){
        },
        warn: function(){
        }
        // any other console functions you using in your code
    };
}

/**
 * Créé le logger pour débugger
 * @param {String} jsFileName nom du fichier js qui appel la méthode
 */
Wizishop.debug = function(){
    if (typeof(Wizishop.myLogReader) == "undefined" && typeof(YAHOO.widget.LogReader) != "undefined") {
        var myConfigs = {
            width: "300px",
            height: "30em",
            fontSize: "10px",
            footerEnabled: true
        };
        var myContainer = document.body;
        Wizishop.myLogReader = new YAHOO.widget.LogReader(myContainer, myConfigs);
    }
}

//Alias
var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, DDM = YAHOO.util.DragDropMgr, YUC = YAHOO.util.Connect, YUA = YAHOO.util.Anim, YL = YAHOO.lang;
YUC.a = YUC.asyncRequest;
Dom.g = Dom.get;
Dom.gC= Dom.getElementsByClassName;


Wizishop.firefbugDetect = function(){
    if (typeof(console) != "undefined" && "firebug" in console && document.location.host == 'admin.wizishop.com') {
       	var block = 
			'<div class="firebug">'+
				'Pour obtenir de meilleures performances sur WiziShop, nous vous suggérons de désactiver Firebug'+
			'</div>';
		Dom.g("header").innerHTML += block;
    }
}

Event.onAvailable("menu", Wizishop.firefbugDetect);

Wizishop.IEDetect = function(){
    if (document.location.host.match('admin.wizishop.com') || document.location.host.match('admin2.wizishop.com')) {
        var flash = {
            vers: 10,
            url: 'http://get.adobe.com/fr/flashplayer/'
        }
        
        var browsers = [{
            nom: 'firefox',
            version: 3.6,
            url: 'http://www.mozilla-europe.org/fr/firefox/'
        }, {
            nom: 'chrome',
            version: 4,
            url: 'http://www.google.com/chrome'
        
        }, {
            nom: 'opera',
            version: 9.8,
            url: 'http://www.opera.com/download/'
        }, {
            nom: 'safari',
            version: 4,
            url: 'http://www.apple.com/fr/safari/download/'
        }, {
            nom: 'explorer',
            version: 8,
            url: 'http://www.microsoft.com/france/windows/products/winfamily/ie/ie8/default.aspx'
        }, ]
        
        var msg = '';
        for (var i in browsers) {
			
            if (browsers[i].nom == Utilities.browserDetect.browser.toLowerCase() && browsers[i].version > Utilities.browserDetect.version) {
				msg += '<li>Une version plus récente de votre  <strong>navigateur Internet</strong> existe, <a target="_blank" href="' + browsers[i].url + '">nous vous conseillons de l\'installer</a></li>';
            }
        }
        
        if (YAHOO.util.FlashDetect.major < flash.vers) {
            msg += '<li>Une version plus récente de votre <strong>lecteur Flash</strong> existe, <a target="_blank" href="' + flash.url + '">nous vous conseillons de l\'installer</a></li>';
        }
        
        if (msg != '') {
            var block = '<ul class="firebug">' +
            msg +
            '</ul>';
            Dom.g("header").innerHTML += block;
        }
        
    }
}

Event.onAvailable("menu", Wizishop.IEDetect);

//Event.onAvailable("content", Wizishop.debug);

$j = jQuery.noConflict();

//Quand on clic dans l'input texte du formulaire de recherche
Event.on('textSearch', 'focus', function() {
	if(this.value == 'Tapez votre recherche ici'){
		this.value = '';
	}
})

Event.on('textSearch', 'blur', function() {
	if(this.value == ''){
		this.value = 'Tapez votre recherche ici';
	}
})

if(typeof(JSON) != 'undefined'){
	YL.JSON = JSON;
}

window.alert = function(message) {
	if (!Wizishop.alert) {
		// Define various event handlers for Dialog
		var handleOk = function(){
			this.hide();
		};
		
		Ut.DomHelper.insertFirst(document.body, '<div id="wiziAlert"><div class="hd"></div></div>');
		
		Wizishop.alert = new YAHOO.widget.SimpleDialog("wiziAlert", {
			width: "300px",
			zIndex: 99999,
			fixedcenter: true,
			visible: false,
			draggable: false,
			close: false,
			modale: true,
			underlay: "none",
			text: '<p>'+message+'</p>',
			icon: YAHOO.widget.SimpleDialog.ICON_WARN,
			constraintoviewport: true,
			buttons: [{
				text: "<span>Ok</span>",
				handler: handleOk,
				isDefault: true
			}]
		});
		
		Wizishop.alert.render();
		Wizishop.alert.setHeader('Attention');
	}
	if(!message.match('<ul>'))
		Wizishop.alert.setBody('<p>'+message+'</p>');
	else
		Wizishop.alert.setBody(message);
	Wizishop.alert.bringToTop();
	Wizishop.alert.show();
}


//window.confirm = function(message) {
//	if (!Wizishop.confirm) {
//		// Define various event handlers for Dialog
//		 handleYes = function(){
//			this.hide();
//			return true;
//		};
//		
//		var handleNo = function() {
//			this.hide();
//			return false;
//		};
//		
//		Ut.DomHelper.append(document.body, '<div id="wiziConfirm"><div class="hd"></div></div>');
//		Wizishop.confirm = new YAHOO.widget.SimpleDialog("wiziConfirm", {
//			width: "300px",
//			fixedcenter: true,
//			visible: false,
//			draggable: false,
//			close: false,
//			text: '<p>'+message+'</p>',
//			icon: YAHOO.widget.SimpleDialog.ICON_WARN,
//			constraintoviewport: true,
//			buttons: [{
//				text: "<span>Oui</span>",
//				handler: handleYes,
//				isDefault: true
//			},
//			{
//				text: "<span>Annuler</span>",
//				handler: handleNo
//			}]
//		});
//		
//		Wizishop.confirm.render();
//		console.log("laa");
//	}
//	Wizishop.confirm.setHeader('Attention');
//	Wizishop.confirm.setBody('<p>'+message+'</p>');
//	Wizishop.confirm.show();
//}

Wizishop.sendAjaxError = function(file, fnName, reponse, param) {
	YUC.a('POST','/_includes/dataerror.php', null, 'action=ajaxerror&file='+file+'&fnName='+fnName+'&param='+param+'&reponse='+reponse);
}

Wizishop.login = {
	dialog:null,
	init: function() {
		var content = 
		'<div class="hd"><span>Identification</span><span id="wiziLoginLoading"></span></div>'+
		'<div class="bd">'+
			'<p>Attention vous avez été déconnecté, vous devez vous reconnecter pour pouvoir continuer.</p>'+
			'<form name="loginform" id="loginform" action="/_ajax/session/login.php" method="post">'+
				'<p><label for="wizi_mail">Identifiant</label><input type="text" name="wizi_mail" id="wizi_mail" value="" />.wizishop.com</p>'+
				'<p><label for="wizi_pass">Mot de passe</label><input type="password" name="wizi_pass" id="wizi_pass" value="" /></p>'+
			'</form>'+
			'<p class="error" style="display:none" id="wiziLoginError">Identifiant ou mot de passe incorrect.</p>'+
		'</div>';
		Ut.DomHelper.insertFirst(document.body, '<div id="wiziLogin">'+content+'</div>');
		
		var loader = new Ut.panelLoading('wiziLoginLoading');
		
		var handleSubmit = function() {
			loader.start();
			this.submit();
		};
		var handleExit = function() {
			window.location = '/ident.php';
		};
		
		var handleSuccess = function(xhr) {
			var jsonstr = xhr.responseText;
			try {
				var connected = YL.JSON.parse(jsonstr);
			}
			catch(e) {
				Wizishop.sendAjaxError('wizishop.js', 'Wizishop.login : handleSuccess', jsonstr);
			}
			loader.end();
			if(connected){
				Wizishop.login.hide();
				Ut.hide('wiziLoginError');
			}
			else {
				Ut.show('wiziLoginError');
			}
			
			Dom.g('loginform').reset();
		}
		
		var handleFailure = function() {
			
		}
		
		this.dialog = new YAHOO.widget.Dialog("wiziLogin", {
			width: "500px",
			zIndex: "1500",
			fixedcenter: true,
			visible: false,
			draggable: false,
			close: false,
			modal:true,
			hideaftersubmit: false,
			underlay: "none",
			constraintoviewport: true,
			 buttons :  [{ text:"<span>Identification</span>", handler:handleSubmit, isDefault:true },{ text:"<span>Quitter l'administration</span>", handler:handleExit, isDefault:true }]
		});
		
		this.dialog.callback = { success: handleSuccess,
						 failure: handleFailure };

		
		this.dialog.render();
		
		this.dialog.validate = function(){
			var data = this.getData(); 
			if(data.wizi_mail != '' && data.wizi_pass != '') {
				return true;
			}
		}
	},
	
	show: function(){
		if(this.dialog == null){
			this.init();
		}
		this.dialog.show();
	},
	
	hide:function(){
		if(this.dialog == null){
			return ;
		}
		this.dialog.hide();
	}
}
Wizishop.checkSessionCpt = 0;

Wizishop.checkSession = function(exigent){
	var href = window.location.href;
	
	if(href.match(new RegExp("admin2.wizishop.com", "gi"))){
		//console.info('pas de verrif session');
		return;
	}
	
	if(typeof(exigent) == "undefined"){
		exigent = true;
	}
  
    if (!href.match(new RegExp("admin.wizishop.com", "gi")) && !href.match(new RegExp("admin2.wizishop.com", "gi"))) {
        return;
    }
    if (href.match(new RegExp("ident.php", "gi")) || href.match(new RegExp("lost-password", "gi")) ) {
        return;
    }
    YUC.a('POST', '/_ajax/session/session.php', {
        success: function(xhr){
            var jsonstr = xhr.responseText;
            try {
                var json = YL.JSON.parse(jsonstr);
            } 
            catch (e) {
                Wizishop.sendAjaxError('wizishop.js', 'Wizishop.checkSession', jsonstr);
            }
            
            if (!json) {
                Wizishop.checkSessionCpt++;
				if(xhr.argument.exigent){
					Wizishop.login.show();
				}
                else if (Wizishop.checkSessionCpt > 1) {
                    Wizishop.login.show();
                    Wizishop.checkSessionCpt = 0;
                }
            }
            else {
                Wizishop.login.hide();
            }
        },
		argument: {
			exigent:exigent
		}
    })
}

Wizishop.timerCheckSession = function() {
	YL.later(5000, this, function() {
		Wizishop.checkSession(false);
	},null,true);
}

Event.on(window, 'load', Wizishop.timerCheckSession);


if (YAHOO.util.History) {
	YAHOO.util.History.getBookmarkedState = function(module){
		var i, len, idx, hash, states, tokens, moduleName;
		
		if (typeof module !== "string") {
			throw new Error("Missing or invalid argument");
		}
		
		// Use location.href instead of location.hash which is already
		// URL-decoded, which creates problems if the state value
		// contained special characters...
		idx = top.location.href.indexOf("#");
		if (idx >= 0) {
			hash = top.location.href.substr(idx + 1);
			states = hash.split("&");
			for (i = 0, len = states.length; i < len; i++) {
				tokens = states[i].split("=");
				if (tokens.length === 2) {
					moduleName = tokens[0];
					if (moduleName === module) {
						return decodeURIComponent(tokens[1]);
					}
				}
			}
		}
		
		return null;
	}
}


Event.onDOMReady(function(){
	if(!Dom.inDocument('ongletMessagerie')){
		return ;
	}
	
    if (Dom.hasClass(Dom.g('ongletMessagerie').parentNode, 'current') || !Dom.inDocument('nbInboxPreHeader')) 
        return;
    
    var attributes = {
        backgroundColor: {
            from: '#000',
            to: '#f7a42f'
        }
    };
    var anim = new YAHOO.util.ColorAnim('ongletMessagerie', attributes);
    anim.onComplete.subscribe(function(){
        setTimeout(function(){
            var attributes = {
                backgroundColor: {
                    from: '#f7a42f',
                    to: '#000'
                }
            };
            var anim2 = new YAHOO.util.ColorAnim('ongletMessagerie', attributes);
            anim2.onComplete.subscribe(function(){
                Dom.setStyle('ongletMessagerie', 'background', '');
            });
            anim2.animate();
        }, 400);
    })
    
    
    setTimeout(function(){
        anim.animate();
    }, 1000)
	
  
})