/*
var timeout    = 500;
var closetimer = 0;
var ddmenuitem = 0;

function jsddm_open()
{  jsddm_canceltimer();
   jsddm_close();
   ddmenuitem = $(this).find('ul.filter_listing').css('visibility', 'visible'); }

function jsddm_close()
{  if(ddmenuitem) ddmenuitem.css('visibility', 'hidden'); }

function jsddm_timer()
{  closetimer = window.setTimeout(jsddm_close, timeout); }

function jsddm_canceltimer()
{  if(closetimer)
   {  window.clearTimeout(closetimer);
      closetimer = null;}}
*/

var PlayList = {};

function getFlashMovieObject(movieName){
  if (window.document[movieName]) 
  {
      return window.document[movieName];
  }
  if (navigator.appName.indexOf("Microsoft Internet")==-1)
  {
    if (document.embeds && document.embeds[movieName])
      return document.embeds[movieName]; 
  }
  else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
  {
    return document.getElementById(movieName);
  }
}

function WPAP_play(id)
{
    var movie = getFlashMovieObject(id);
    if (movie != undefined)
	movie.SetVariable("jsCommand", "play");
}

function WPAP_stop(id)
{
    var movie = getFlashMovieObject(id);
    if (movie != undefined)
	movie.SetVariable("jsCommand", "stop");
}




function WPAP_start_play(playerID) {
    if (PlayList == undefined) return;

    for (var key in PlayList)
    {
	if (key != playerID)
	    WPAP_stop(key);
    }

    WPAP_play(playerID);
}


function WPAP_stop_play(playerID) {
    if (PlayList == undefined) return;

    //playerID = "mv_" + playerID;

    var found = false;
    var lasttab;
    for (var key in PlayList)
    {
	if (key == playerID)
	{
	    found = true;
	    lasttab = PlayList[key];
	    continue;
	}
	if (found)
	{
	    if (lasttab != PlayList[key])
	    {
		$("#a_" + PlayList[key]).trigger("click");
		setTimeout(function() {
		    WPAP_play(key);
		}, 1000);
	    } else WPAP_play(key);

	    return;
	}
    }
}


function nativeReplace(id, data)
{
    var anchor = document.getElementById(id);
    var span = document.createElement("span");
    span.innerHTML = data;
    anchor.parentNode.replaceChild(span, anchor);
}


$(document).ajaxSuccess(function() {
    try {
	Cufon.refresh();
    } catch (err) {
    }
});

function updateCField()
{
    var parent = $(this);
    while (!parseInt(parent.attr("count")) > 0)
    {	
	parent = parent.parent(); 
	if (parent == null)
	    return false;
    }

    var data = Array();
    var link = null;

    parent.children("." + parent.attr("link")).each( function() {
	var child = $(this);
	if (link == null) {	link = "#" + child.attr("link");	}
	var childData = Array();

	child.children().each( function() {
	    var tag = $(this);

	    if (tag.prop("tagName") == "INPUT" || tag.prop("tagName") == "SELECT")
	    {
		if (parseInt(tag.val()) == 0)
		{
		    childData.length = 0;
		    return false;
		}
		childData[childData.length] = tag.val();
	    }
	});
	if (childData.length > 0)
	    data[data.length] = childData;
    });

    var result = "";

    for (var i = 0; i < data.length; i++) {	result += data[i].join(':') + ';';	}

    $(link).val(result);

    return false;
}

function bindCField(id)
{
    var e = "#" + id;
    $(e + " > ." + $(e).attr("link") + " > select").bind("change", updateCField);
    $(e + " > ." + $(e).attr("link") + " > input").bind("change", updateCField);
}

String.prototype.replaceAllx = function( strTarget,  strSubString ){
 var strText = this;
 var intIndexOfMatch = strText.indexOf( strTarget );
  
 // Keep looping while an instance of the target string
 // still exists in the string.
 while (intIndexOfMatch != -1){
 // Relace out the current instance.
 strText = strText.replace( strTarget, strSubString )
  
 // Get the index of any next matching substring.
 intIndexOfMatch = strText.indexOf( strTarget );
 }
  
 // Return the updated string with ALL the target strings
 // replaced out with the new substring.
 return( strText );
}

/*
Object.extend = function(destination, source) {
    for (var property in source) {
        if (source.hasOwnProperty(property)) {
            destination[property] = source[property];
        }
    }
    return destination;
};
*/

function refreshCField()
{
    $(".cfield_add").each(function() {
	bindCField($(this).attr("id"));
    });
}


function reasonUpdate()
{
    var container = "orderinfo";

    $(".order_confirm_action").click( function() {
	if ( $("#delete_reason_"+$(this).attr("discid")).val().length <= 5 )
	    return false;
        $.ajax({ url: $(this).attr("link"), type: "POST", dataType: "html", data: {"order_action" : "delete", "discid" : $(this).attr('discid'), "reason" : $("#delete_reason_"+$(this).attr("discid")).val()}, success: function(data) {
	    window.location = window.location.href;
	    return;
            if ($.browser.msie) {
                if ($("#jcart_wrapper").length <= 0)
                {
                    $("#"+container).before("<div id=\""+container+"\"></div>").remove();
                }

                document.getElementById(container).innerHTML = data;
            } else {
                $("#"+container).html($(data).html());
            }
            $(".jcart-hide").remove();
            Cufon.refresh();
            rerefresher();
                
        }});
    });
}


function actionsUpdate() {
    $("img.order_delete_button").click( function () {
        if ($(this).attr('status') == undefined || $(this).attr('status') == "off")
        {
	    var action ="<tr id='action_"+$(this).attr("discid")+"'><td colspan='10'><table width='100%'><tr><td align='center' style='font-size:11px; color: #eee;'>Te rugam sa mentionezi motivul pentru care doresti anularea comenzii pentru acest produs</td></tr><tr><td align='right' style='border: 1px solid #aaa;padding: 2px;'>"+
	    "<select id='delete_reason_"+$(this).attr("discid")+"' name='delete_reason' discid='"+$(this).attr("discid")+"'>"+
	        "<option value=''>Selecteaza motiv</option>"+
	        "<option value='livrarea dureaza prea mult'>livrarea dureaza prea mult </option>"+
	        "<option value='l-am gasit mai ieftin la alt comerciant'>l-am gasit mai ieftin la alt comerciant </option>"+
	        "<option value='doream sa il fac cadou'>doream sa il fac cadou </option>"+
	        "<option value='alte motive'>alte motive</option>"+
	    "</select>"+
	    "<button class='order_confirm_action' discid='"+$(this).attr("discid")+"' link='"+$(this).attr("link")+"'>Anuleaza</button></td></tr></table></td></tr>";
	    $(this).parent().parent().after(action);
	    $(this).attr('status', 'on');
	    reasonUpdate();
	} else {
	    $("#action_"+$(this).attr("discid")).remove();
	    $(this).attr('status', 'off');
	}
    });
}


function rerefresher()
{

    if (jQuery.browser.msie) {
        $('input:radio').click(function () {
            this.blur();
            this.focus();
        });
    }


    $('.refresher input[type="radio"]').change(function() {
	var link = $(this).parent().attr('link');
	var container = $(this).parent().attr('container');
	if (container == null || container == undefined || container.length == 0)
	    container = "jcart";
//	alert(container + " " + link);
	$.ajax({ url: link, type: "POST", dataType: "html", data: {"name" : $(this).attr('name'), "value" : $(this).attr('value')}, success: function(data) {
		//alert($(data).find("#jcart").length);
		//alert($(data).text());
//		var content = ($.browser.msie) ? $(data).context.xml : $(data).html();
	        if ($.browser.msie) {
		    //data = data.replaceAllx("\'", "\"");
		    //alert($(data).html());
		    if ($("#jcart_wrapper").length <= 0)
		    {
			$("#"+container).before("<div id=\"jcart_wrapper\"></div>").remove();
		    }
		    document.getElementById('jcart_wrapper').innerHTML = data;
		}
		else {
		    $("#"+container).html($(data).html());
		}


		$(".jcart-hide").remove();
		Cufon.refresh();
		rerefresher();
	        actionsUpdate();
	}});
    });
}


$(document).ready(function docready() {

    if (jQuery.browser.msie) {
        $('input:radio').click(function () {
            this.blur();
            this.focus();
        });
    }

    actionsUpdate();


    $(".niche_prop").change(function() {
	var id = $(this).val();
	var data = $("#niche_prop").val();
	var arr = data.split(',');
	var key = jQuery.inArray(id, arr);

	if (data == null) data = "";

	if (key == -1 && $(this).is(':checked'))
	{
	    if (data.length > 0)
		$("#niche_prop").val(data+","+id);
	    else
		$("#niche_prop").val(id);
	}
	else
	{
	    arr.splice(key, 1);
	    $("#niche_prop").val(arr.join(','));
	}
	
    });

    $("button.activate").click(function() {
	var link = "#" + $(this).attr('link');
	if ($(link).attr('state') != 'on')
	    $(link).show().attr('state', 'on');
	else
	{
	    $(link).hide().attr('state', 'off');
	    $(link).children("input").val("");
	}
	return false;
    });

    $(".switcher").change(function() {
	if ($(this).is(":checked"))
	    $(this).val($(this).attr("on"));
	else
	    $(this).val($(this).attr("off"));
    });

    if ($('#searchbar').length > 0)
    {
	$('#searchbar').focus();
	var options, a;
	var search_where = $("#searchbar-where").val();
	if (search_where == 2)
	    $('#searchbar').attr('status', '0');

	options = { serviceUrl:'/ajax/search.php',
	    minChars:2,
	    maxHeight:250,
	    width:450,
	    zIndex: 9999,
	    deferRequestBy: 50 //miliseconds
	};

    	searchbar = $('#searchbar').autocomplete(options);

	$("#searchbar-where").change(function() {
	    var search_where = $("#searchbar-where").val();
	    if (search_where == 2)
		$('#searchbar').attr('status', '0');
	    else
		$('#searchbar').attr('status', '1');
	});
    }

    $("button.replicate").click(function() {
	var link = "#" + $(this).attr('link');
	var link_2 = $(link).attr('link');
	$(link).append($("#" + link_2 + "_0").clone().attr('id', link_2 + "_" + $(link).attr('count')));
	$("#" + link_2 + "_" + $(link).attr('count') + " > select").val("0");
	$("#" + link_2 + "_" + $(link).attr('count') + " > input").val("1");
	$(link).attr('count', parseInt($(link).attr('count')) + 1);
	refreshCField();

	return false;
    });

    $(".optiontree").change(function() {
	var link = $(this).attr("link");
	var item = $(this).attr("id");
	var selected = "#" + item + " option:selected";
	var parent = $(selected).attr("parent");
	if (parent != undefined && parent.length > 0)
	    $("#"+link).val(parent);
    });

    function filterClick(e) {
	if ( $(e).prop("tagName") != "INPUT" )
	{
	    var field = $(e).children("input.filter_input");
	} else {
	    var field = $(e);
	}
	var value = false;
	if (!field.is(":checked"))
	    value = "checked";
//	alert(value);
	field.attr("checked", value);
	field.trigger("foo");
    }

    $("ul.subnav>div>li,").click(function() {
	filterClick(this);
    });

    $("ul.subnav>li").click(function () {
	filterClick(this);
    });

    $(".filter_input").click(function () {
	filterClick(this);
    });


    $(".filter_input").bind("foo", function() {

	if ( $(this).parent().parent().parent().attr("id") == "f1" ) {
	    //alert("s");
	    if ( $(this).is(":checked") ) {
		if ($(this).attr("name") == "f1[0]") {
		    var other = $(this).parent().parent().children("li:nth-child(2)").children("input");
		    other.attr("checked", false);
		}
		else if ($(this).attr("name") == "f1[1]") {
		    var other = $(this).parent().parent().children("li:nth-child(1)").children("input");
		    other.attr("checked", false);
		}
	    }
	}

	//alert("je");

	var form = $("#filter_form");

	var $inputs = $('#filter_form :input');

	var values = jQuery.parseJSON($(form).attr('parameters'));
	$inputs.each(function() {
	    if ($(this).is(":checked"))
		values[this.name] = "on";
	    else
    		values[this.name] = "off";
	});

	//alert(values);

	var parent = $(this);
	var input  = parent;


        while(!$(parent).parent().hasClass("head") && parent != null && parent != undefined)
        {
	    //alert (parent.get(0).nodeName.toLowerCase());
	    parent = $(parent).parent();
	}

	var ok = false;
	
	var section_id = $(parent).parent().attr("id");

	var $section = $("#" + section_id + " :input");
	$section.each(function() {
	    if ($(this).is(":checked"))
	    {
	        ok = true;
	        return;
	    }
	});

	if (ok)
	{
	    //if ( ! $(parent).parent().hasClass("subnav_selected") )
	    $(parent).parent().addClass("subnav_selected");
	} else {
	    $(parent).parent().removeClass("subnav_selected");
	}

	$.post("/main/ajaxsearch", values, function(data) {
	    $("#ajax_container").before(data).remove();
	    Cufon.refresh();
	    jcartready();
	});

    });


    $("#reset_filter_button").click(function() {
	var $inputs = $('#filter_form :input');
	$inputs.each(function() {
	    $(this).attr('checked', false);
	});
    });

    if ($("#filter_form").length > 0)
	$("#filter_form")[0].reset();

    
    refreshCField();
    rerefresher();

    //$("ul.subnav").parent().append("<span></span>"); //Only shows drop down trigger when js is enabled (Adds empty span tag after ul.subnav*)  
   
    $("ul.topnav>li.head").click(function() { //When trigger is clicked...
	//Following events are applied to the subnav itself (moving subnav up and down)  
        //$(this).find("div").show();
	var hasdiv;
	if ($(this).find("div").length > 0)
	{
	    hasdiv = true;
	}
	else {
	    hasdiv = false;
	}
	if (hasdiv) {
	    $(this).find("ul.subnav").show().slideDown('fast');
	    //$(this).find("div").slideDown('fast'); //Drop down the subnav on click  
	}
	else {
	    $(this).find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click  
	}

	$(this).hover(function() {  
	}, function(){
//	    if ($(this).find("div").length > 0) {
//		$(this).find("div").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
//		$(this).find("ul.subnav").hide();
//		$(this).find("div").show();
//	    }
//	    else {
		$(this).find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up  
//	    }
	});
	if ($(this).find("ul.subnav").length <= 0)
	    return false;
	else
	    return true;
    }).hover(function() {
	$(this).addClass("subhover"); //On hover over, add class "subhover"
    }, function(){  //On Hover Out
        $(this).removeClass("subhover"); //On hover out, remove class "subhover"
    });

    /*
    $('#jsddm > li').bind('mouseover', jsddm_open);
    $('#jsddm > li').bind('mouseout',  jsddm_timer);
    */

});

//document.onclick = jsddm_close;
