<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{$language.lblProducts}</title>
{include file='CommonJavaScript.tpl'}
<link rel="stylesheet" type="text/css" href="{$view_styles}/popup.css" media="screen" />
<link href="{$view_styles}/jqueryui.plugin.css" rel="stylesheet" type="text/css" />
<link href="{$view_styles}/jquery-ui-1.8.19.custom.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="{$view_styles}/ui.daterangepicker.css" />
{form->rootpath_script}
{form->basepath_script}
<style>
.viewcombination{
margin: 5px;
font-size: 13px;
width: 10px;
}
.expandedSection{
display: block;
margin: 10px 0 0 60px;
}
</style>	
</head>
<body >
<div class="popup-block btn-flt-spc">
	<div class="clear"></div>
	<!-- Search container starts --> 
        {form->start name="frmSearchProducts" action="" method="post"}          
			<div class="search_container clearfix">
				<div class="inner">
					<ul class="clearfix">
						<li class="column wide ">
							<p class="label-field01">{$language.lblProductIDTitle}</p> 
							<span class="form-field01">
								{form->textbox name="searchProductName" class="text-box" style="width:95%;"} 
							</span>
						</li>
						<li class="column wide">				 
							<p class="label-field01">{$language.lblCategory}</p>
							<span class="form-field01"> 
								{form->select class="select-box" name="searchProductCategory" options=$resCategories caption="->{$language.lblSelect}"}
							</span>
						</li> 
						<li class="column wide">				 
							<p class="label-field01">{$language.lblMerchant}</p>
							<span class="form-field01"> 
								{form->select class="select-box" name="searchBusiness" options=$resBusiness caption="->{$language.lblSelect}"}
							</span>
						</li>
						<li class="column wide">				 
							<p class="label-field01" >{$language.lblMarginProfit}</p>
							<span class="form-field01">
								{form->select 
						name="searchMarginType" class="select-box width75per "
						options="per->Percentage( >= )~*val->Value( >= )"
						value="per"
						} 
								{form->textbox name="searchMargin" class="text-box width20per" }
							</span>
						</li> 
						<li class="column">
							<p class="label-field01">&nbsp;</p>
							<span class="btn_fltg">{form->submit name="submitProductSearch" id="submit" class="grayBtn2"  value=$language.lblSearch}              
							{html->anchor href="promotions/ajaxLoadProducts/{$additionalLink}" class="action-link top-spc" content="{$language.lblListAll}"}</span>
						</li>           
					</ul>
				</div>
			</div>
		{form->close}
    <!-- Search container ends --> 
	<div id="common_message"></div>
	{if $resProducts|@count>0} 
		<div class="form_listing02 clearfix">
			<div class="grid_table00"> 
				<table width="100%" border="0" cellspacing="0" cellpadding="0"   >
					<thead>
						<tr>
							<th align="left" valign="middle"  width="30%" colspan="2">
								<span class="chkd-item">
									{form->checkbox class="listAllCheckBoxItems v-aline fixing_left"}
								</span>
								&nbsp; {$language.lblProduct}
							</th>
						</tr>
					</thead>
					<tbody>
						{foreach from=$resProducts item="resProductList" key="key"}
							{assign var="productID" value=$resProductList.productID} 
							<tr>
								<td align="left" valign="middle" colspan="2">
									<span class="chkd-item">
									{if isset($resProductList.options)}									
									{assign var="optionsarry" value=$resProductList.options}
									{else}
									{assign var="optionsarry" value=$resProductList.options|default:array()}
									{/if}
									{if isset($resProductList.customOptions)}									
									{assign var="coptionsarry" value=$resProductList.customOptions}
									{else}
									{assign var="coptionsarry" value=$resProductList.customOptions|default:array()}
									{/if}
										{assign var="optionsCount" value=$optionsarry|count} 
										{assign var="customOptionsCount" value=$coptionsarry|count} 
										{assign var="totalOptionsCount" value=$optionsCount+$customOptionsCount}
										{if $alloptions eq "Yes"}
											{if $totalOptionsCount > 0}
												{html->anchor class="viewcombination" rel=$productID caption="+" title={$language.lblOptions}}
											{else if $totalOptionsCount == 0}
												&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
											{/if}
										{else}	
											{if $resProductList.combinationCount|default:'' > 0}
												{html->anchor class="viewcombination" rel=$productID caption="+" title={$language.lblViewCombinations}}
											{else if $resProductList.combinationCount|default:'' == 0}
												&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
											{/if}
										{/if}	
										{form->checkbox class="selectCheckBoxItems v-aline fixing_left" name="check_$productID" value=$productID}
										<span id="hiddenTitle_{$productID}" class="hiddenTitle hide">{$resProductList.productTitle}</span>
										<span id="div_err_customOptions_{$productID}" class="div_err_customOptions message_validation hide" style="display:inline-block;float: right;"><span>{$language.errEnterCustomOptions}</span></span>
									</span>
									<label for="check_{$productID}">
										<strong>{$resProductList.productTitle}</strong>
									</label>
									{if $alloptions eq "Yes" && $totalOptionsCount > 0}
										<span class="expandedSection hide" id="expandedSection_{$productID}">
											{if $optionsCount > 0}
												{if $resProductList.optionsType eq "combinations"}	
													<p>{$language.lblCombinations}<br/><br/></p>
												{else if $resProductList.optionsType eq "variants"}	
													<p>{$language.lblVariants}<br/><br/></p>
												{/if}
												{form->hidden name="optionsType_$productID" value=$resProductList.optionsType}	
												{foreach from=$resProductList.options item="optionList"}
													{form->checkbox id="checkSub_{$optionList['id']}" name="checkSub_{$optionList['id']}" value="{$optionList['id']}" class="selectCheckBoxSubItems v-aline fixing_left" optiontype="{$optionList['optiontype']}"}
													<span class="hiddenSubTitle hide">{$optionList['title']}</span><label for="checkSub_{$optionList['id']}">{$optionList['title']}</label><br/><br/>
												{/foreach}
											{/if}	
											{if $customOptionsCount > 0}
												<div class="customOptionsListContainer">
												<p>{$language.lblCustomOptions} [  {$language.errAllRequired} ]<br/><br/></p>	
												{foreach from=$resProductList.customOptions item="customOptionList"}
													<span style="width:100px;display:inline-block;">
													{$customOptionList.title}&nbsp;&nbsp;&nbsp;&nbsp;
													</span>
													<span class="hiddenCustomOptionSubTitle hide" id="hiddenCustomOptionSubTitle_{$customOptionList.id}">{$customOptionList['title']}</span>
													{form->hidden name="customOptionInputType_{$customOptionList.id}"    value="{$customOptionList.inputType}"}
													{if $customOptionList.inputType eq "select" || $customOptionList.inputType eq "multiselect"}
														{assign var="optionArray" value=''}	
														{assign var="count" value=0}
														{foreach from=$customOptionList.variants key ="customOptionVariantId" item="customOptionVariant"}   
															{$optionArray[$count][0]=$customOptionVariantId}
															{$optionArray[$count][1]=$customOptionVariant|html_entity_decode}
															{assign var="count" value=$count+1}
														{/foreach}
														
														{if $customOptionList.inputType eq "select"}
															{form->select name="customOptionsList_{$customOptionList.id}" class="customOptionsList select-box" style="width:auto;" optionid="{$customOptionList.id}" options=$optionArray}
														{else if $customOptionList.inputType eq "multiselect"}	
															{form->checkbox name="customOptionsListCheckbox_{$customOptionList.id}" options=$optionArray seperator="&nbsp;&nbsp;" class="customOptionsListCheckbox" rel="customOptionsList_{$customOptionList.id}"}	
															{form->hidden name="customOptionsList_{$customOptionList.id}"  class="customOptionsList customOptionsListCheckboxMain"  optionid="{$customOptionList.id}"}	
														{/if}
													{else if $customOptionList.inputType eq "textbox" || $customOptionList.inputType eq "date" || $customOptionList.inputType eq "datetime" || $customOptionList.inputType eq "time"}
														{assign var="additionalClass" value=""}
														{if $customOptionList.inputType eq "date"}
															{assign var="additionalClass" value="enableDatePicker"}
														{else if $customOptionList.inputType eq "datetime"}
															{assign var="additionalClass" value="enableDateTimePicker"}
														{else if $customOptionList.inputType eq "time"}
															{assign var="additionalClass" value="enableTimePicker"}
														{/if}
														{form->textbox maxlength="255" name="customOptionsList_{$customOptionList.id}" class="customOptionsList textbox {$additionalClass}"  optionid="{$customOptionList.id}" style="width:250px;"}
													{else if $customOptionList.inputType eq "textarea"}
														{form->textarea name="customOptionsList_{$customOptionList.id}" rows="6" class="customOptionsList" optionid="{$customOptionList.id}"}
													{else if $customOptionList.inputType eq "file"}
														{form->start name="frmCustomOptionFileUpload" id="frmCustomOptionFileUpload_{$customOptionList.id}" action="promotions/ajaxUpload/" method="post" enctype="multipart/form-data" class="frmCustomOptionFileUpload" custid="{$customOptionList.id}" style="display:inline-block;"}
															{form->upload  name="option_{$productID}_{$customOptionList.id}" id="customOptionFileUpload_{$customOptionList.id}"}
															{form->hidden class="currentTime" name="currentTime" id="currentTime_{$customOptionList.id}"}
															{form->hidden class="customOptionsList" name="custOptionUploadedFileName" id="custOptionUploadedFileName_{$customOptionList.id}" optionid="{$customOptionList.id}"}
															<span id="custOptionUploadedFile_{$customOptionList.id}">
															</span>
															{form->submit name="customOptionFileUploadSubmit" value=$language.lblUpload class="grayBtn2"}
														{form->close}		
													{/if}
													<br/><br/>
												{/foreach}
												</div>
											{/if}
										</span>	
									{else}	
										{if $resProductList.combinationCount|default:'' > 0}
											<span class="expandedSection hide" id="expandedSection_{$productID}"></span>
										{/if}	
									{/if}	
								</td>
                              </tr>									
						{/foreach}
					</tbody>
				</table/>	
			</div>
			<!--Start: Pagination-->
			<div class="fixing_right pagination_outer">
				{paginate->layout  key="page" label_record="{$language.lblRecorsFound}" label_pages="{$language.lblPages}"} 					
				<div class="clear"></div>
			</div>         
			<!--end: Pagination--> 
			<div class="clear"></div>
		</div>
		<div class="submit-block clearfix textto_center floating-btn">
			<span>&nbsp;</span>
			{form->button name="addProductButton" class="blueBtn-1" value=$language.lblPromotionSchemaLinkProducts}
			{$language.lblOr} 
			{html->anchor onclick="parent.$.colorbox.close();" id="cancel" class="grayBtn3" caption="{$language.lblCancel}"}
		</div>
	{else}
        <div class="message_info"> {$language.msgNoRecords}</div>	
	{/if}	
</div>
{html->messages_script id="common_message"}
<script type="text/javascript" src="{$common_js}/jquery.form.js"></script>
<script type="text/javascript" src="{$view_javascript}/jquery-ui-timepicker-addon.js"></script>
<script>
var lblSelectItem ="{$language.lblSelectItem}";	
var errEnterCustomOptions ="{$language.errEnterCustomOptions}";	
var enableQuantity ="{$enableQuantity}";	
var callbackFunction ="{$callbackFunction}";	
var objectid ="{$objectid}";
var alloptions ="{$alloptions}";
var selectedDataObj = [];
var d = new Date();
$(".currentTime").val(d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate() + '-' + d.getHours() + '-' + d.getMinutes() + '-' + d.getSeconds());
$(document).ready(function (){		
	$(document).on('click', ".listAllCheckBoxItems", function () {
		if ($(this).prop("checked") == true) {
			$(".selectCheckBoxItems").prop("checked", "checked");
		} else {
			$(".selectCheckBoxItems").removeAttr("checked");
		}
	});	
	$(document).on('click', ".customOptionsListCheckbox", function () {
		var rel = $(this).attr("rel");
		var checkBoxChecked = [];
		$(".customOptionsListCheckbox[rel='"+rel+"']:checked").each(function () {
			checkBoxChecked.push($(this).val());
		});	
		$("#"+rel).val(checkBoxChecked.join(","));
	});
	$(document).on('click', "#addProductButton", function () {
		if($(".selectCheckBoxItems:checked").size()==0)
		{
			jAlert(lblSelectItem);
			return false;
		} 
		var selectedDataObj = [];
		var errorFound = 0;		
		$('.selectCheckBoxItems:checked').each(function () {        
			var selectedDataOptObj = [];
			var selectedDataCustomOptObj = [];
			errorFound = 0;
			//Custom Options
			var customOptionsListContainer = $(this).parents("td").find(".customOptionsListContainer");
			if(customOptionsListContainer.length>0)
			{
				customOptionsListContainer.find(".customOptionsList").each(function () { 
					var optionidVal = $.trim($(this).val());
					if(optionidVal!="")
					{
						var optionid = $(this).attr("optionid");
						var inputType = $("#customOptionInputType_"+optionid).val();
						var valueText = [];
						if(inputType=="multiselect")
						{
							optionIds = optionidVal.split(",");
							$.each(optionIds, function(index, value) {
							   valueText.push($(".customOptionsListCheckbox[value='"+value+"']").attr("text"));
							});							
						}
						else if(inputType=="select")
						{
							valueText.push($("#customOptionsList_"+optionid+" option[value='"+optionidVal+"']").text());
						}
						selectedDataCustomOptObj.push({
							id: optionid,
							title: $("#hiddenCustomOptionSubTitle_"+optionid).html(),
							value: optionidVal,
							valueText: valueText,
							inputType: inputType,
						});
					}
					else
					{
						errorFound++;
					}	
				});
				if(errorFound>0)
				{
					$("#div_err_customOptions_"+$(this).val()).removeClass("hide");
				}
			}
			//Variants / Combinations
			$(this).parents("td").find(".selectCheckBoxSubItems:checked").each(function () { 
				selectedDataOptObj.push({
					id: $(this).val(),
					title: $(this).next(".hiddenSubTitle").html(),
					optiontype: $(this).attr("optiontype")
				});
			});
			selectedDataObj.push({
				id: $(this).val(),
				title: $(this).next(".hiddenTitle").html(),
				options: selectedDataOptObj,
				customOptions: selectedDataCustomOptObj,
				enableQuantity: enableQuantity,
				optionsType: $("#optionsType_"+$(this).val()).val()
			});
		});
		if(errorFound>0)
		{
			$('html,body').animate({
					scrollTop: $(".message_validation:visible:first").offset().top},
					'slow');
			return false;
		}	
		else
		{
			//console.log(selectedDataObj);return false;
			parent.$.colorbox.close();	
			var fn = window['parent'][callbackFunction];	
			if (typeof fn === "function") 
			{ 
				fn(selectedDataObj);
			}
			else
			{
				parent.addItemFromPicker(selectedDataObj); 
			}
		}	
	});
	$(document).on("click","a.viewcombination",function(){	
		var thisVar = $(this);	
		var thisID = thisVar.attr("rel");
		var currentText = thisVar.text();
		var nextText = "";
		if(currentText=="+")nextText = "-";else nextText = "+";
		thisVar.text(nextText);
		if(currentText=="+")
		{		
			if($("#expandedSection_"+thisID).html()!='')
			{
				$("#expandedSection_"+thisID).removeClass("hide");
				setCheckboxSubSelected();
			}
			else
			{
				$.ajax({
				type: 'POST',
				url: GLOBAL_BASE_PATH + "/promotions/ajaxGetProductCombinationList/",
				data: 'id='+thisID,
				success: function (data) {
					var combn = jQuery.parseJSON(data);
					var combnStr = '';
					$.each(combn, function(index, value) {
						combnStr = combnStr + '<input type="checkbox" id="checkSub_'+value['id']+'" name="checkSub_'+value['id']+'" value="'+value['id']+'" class="selectCheckBoxSubItems v-aline fixing_left" optiontype="combination"><span class="hiddenSubTitle hide">'+value['title']+'</span><label for="checkSub_'+value['id']+'">'+value['title']+'</label><br/><br/>';
					});
					$("#expandedSection_"+thisID).html(combnStr);
					$("#expandedSection_"+thisID).removeClass("hide");
					setCheckboxSubSelected();
				}
				});
			}
		}
		else
		{
			$("#expandedSection_"+thisID).addClass("hide");
		}
	});
	$(document).on('click', ".selectCheckBoxSubItems", function () {
		var parentTd = $(this).parents("td");
		var parentCheckBox = parentTd.find(".selectCheckBoxItems");
		if ($(this).prop("checked") == true) {
			parentCheckBox.prop("checked", "checked");
		} 
		else
		{
			if(parentTd.find(".selectCheckBoxSubItems:checked").length == 0)
			parentCheckBox.removeAttr("checked");
		}
	});
	$(document).on('click', ".selectCheckBoxItems", function () {
		var parentTd = $(this).parents("td");
		if ($(this).prop("checked") == false) {			
			if(parentTd.find(".selectCheckBoxSubItems:checked").length > 0)
			parentTd.find(".selectCheckBoxSubItems:checked").removeAttr("checked");
		}
		else
		{
			if(parentTd.find(".selectCheckBoxSubItems").length > 0)
			parentTd.find(".selectCheckBoxSubItems").prop("checked", "checked");
		}
	});
	$('.frmCustomOptionFileUpload').ajaxForm({
		complete: function (xhr) 
		{			
			userUploadedImageArray = xhr.responseText;
			var JSONuserUploadedImageArray = JSON.parse(userUploadedImageArray);			
			if (JSONuserUploadedImageArray.isError == 'Yes' && typeof JSONuserUploadedImageArray != 'null') 
			{				
				if(typeof JSONuserUploadedImageArray.customOptions != "undefined")
				{
					$("#customOptionFileUpload_"+JSONuserUploadedImageArray.customOptions.id).val('');
				}	
				jNotifyShow(JSONuserUploadedImageArray.errorMessage, "common_message", "message_error");
				return true;
			}
			else
			{
				$("#custOptionUploadedFile_"+JSONuserUploadedImageArray.customOptions.id).html(JSONuserUploadedImageArray.customOptions.filename);
				$("#custOptionUploadedFileName_"+JSONuserUploadedImageArray.customOptions.id).val(JSONuserUploadedImageArray.customOptions.filename);
				$("#customOptionFileUpload_"+JSONuserUploadedImageArray.customOptions.id).val('');
				$("#check_"+JSONuserUploadedImageArray.customOptions.productID).prop("checked", "checked");
			}
		}
	});	
});
{literal}	
$(document).ready(function ()
{	
		$('.enableDatePicker').datepicker({showTime: false,					 
						  dateFormat:datePickerDateFormat});
		$('.enableDateTimePicker').datetimepicker({dateFormat:datePickerDateFormat,currentText:lblCurrentMonth});
		$('.enableTimePicker').timepicker({ampm: false,stepMinute: 15});	
});
{/literal}
setCheckboxSelected();
function setCheckboxSelected()
{
	if(objectid!='')
	{
                if(window.parent.$("#"+objectid).val()!='' && window.parent.$("#"+objectid).val() != "undefined")
                    var currentSelectedElementValue = $.parseJSON(window.parent.$("#"+objectid).val());
                else
                    var currentSelectedElementValue = '';
		var selectedIds = [];
		if(currentSelectedElementValue)
		{
			$.each(currentSelectedElementValue, function( key, value ) {
				selectedIds.push(value.productID);
			});
		}	
	}	
	else
	{
		var currentSelected = parent.currentPopupPicker.nextAll().find(".popupPickerDataValues:first").val();
		var selectedIds = currentSelected.split(",");
	}	
	if(selectedIds)
	{		
		$('.selectCheckBoxItems').each(function () { 
			if($.inArray($(this).val(),selectedIds)>-1)
			$(this).prop("checked", "checked");
		});		
	}
}
function setCheckboxSubSelected()
{
	var subSelectionData = [];
	if(objectid!='')
	{
                if(window.parent.$("#"+objectid).val()!='' && window.parent.$("#"+objectid).val() != "undefined")
                    var currentSelectedElementValue = $.parseJSON(window.parent.$("#"+objectid).val());
                else
                    var currentSelectedElementValue = '';
		var selectedIds = [];
		if(currentSelectedElementValue)
		{
			$.each(currentSelectedElementValue, function( key, value ) {
				var combinations = value.combinations.split(",");
				if(combinations)
				{
					$.each(combinations, function( key, value ) {
						$(".selectCheckBoxSubItems[optiontype='combinations'][value='"+value+"']").prop("checked", "checked");
					});
				}
				var options = value.variants.split(",");
				if(options)
				{
					$.each(options, function( key, value ) {
						$(".selectCheckBoxSubItems[optiontype='productoptions'][value='"+value+"']").prop("checked", "checked");
					});
				}	
				var customOptions = value.customOptions;
				if(customOptions)
				{
					$.each(customOptions, function( key, customOptionsData ) {
						var customOptionId = customOptionsData.id;
						var customOptionValue = customOptionsData.value;
						var customOptionIdType = $("#customOptionInputType_"+customOptionId).val();
						if(customOptionIdType=="multiselect")
						{
							var customOptionValues = customOptionValue.split(",");
							$.each(customOptionValues, function( customOptionValuesKey, customOptionValuesVal ) {
								$(".customOptionsListCheckbox[rel='customOptionsList_"+customOptionId+"'][value='"+customOptionValuesVal+"']").prop("checked", "checked");
							});
						}
						else if(customOptionIdType!="file")
						{
							$("#customOptionsList_"+customOptionId).val(customOptionValue);
						}
						else if(customOptionIdType=="file")
						{
							$("#custOptionUploadedFileName_"+customOptionId).val(customOptionValue);
							$("#custOptionUploadedFile_"+customOptionId).html(customOptionValue);
						}
					});
				}	
			});
		}	
	}	
	else
	{
		var subSelectionLength = parent.currentPopupPicker.nextAll().find(".popupPickerDataList:first").find(".popupPickerDataSubValues").length;
		parent.currentPopupPicker.nextAll().find(".popupPickerDataList:first").find(".popupPickerDataSubValues").each(function () { 
			subSelectionData.push($(this).val());
		});
	}	
	if(subSelectionData)
	{		
		$('.selectCheckBoxSubItems').each(function () { 
			if($.inArray($(this).val(),subSelectionData)>-1)
			$(this).prop("checked", "checked");
		});	
	}
}	
</script>	
</body>
</html>