<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    design
 * @package     base_default
 * @copyright   Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<?php
/**
 * Product list template
 *
 * @see Mage_Catalog_Block_Product_List
 */
?>
<?php
    $_productCollection=$this->getLoadedProductCollection();
    $_helper = $this->helper('catalog/output');
?>
<?php if(!$_productCollection->count()): ?>
<p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p>
<?php else: ?>
<?php echo "custom code starts here";
foreach ($_productCollection as $_product): ?> 
<li>
			<?php $_productNameStripped = $this->stripTags($_product->getName(), null, true); ?>
                    <b><?php echo $_helper->productAttribute($_product, $_product->getName() , 'name'); ?></b>                    
                    <?php echo $this->getPriceHtml($_product, true) ?>
               
                    <?php if($_product->isSaleable()): ?>
                     <form action="<?php echo Mage::getBaseUrl(); ?>multiadd/add" method="post" id="<?php echo $_product->getId()?>">
					<?php
                    $product = Mage::getModel('catalog/product');
					Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($_productCollection);
                    $product->load($_product->getId());
                    $xml = '';
                    $hasAtts = 0;
					$hasAttsIn = 0;
                    $productType = $product->getTypeId();
                    if($productType == "configurable") {
                        $attValConfig = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);  						
						$childIds = Mage::getModel('catalog/product_type_configurable')->getChildrenIds($_product->getId());
						$k=0;
						foreach($childIds as $val_m) :
							foreach($val_m as $val) :
								$main_child_id[$k]=$val;	
								$k++;							
							endforeach;						
						endforeach;
						 $c=0;	
						$xml .= '<table><tr><td width="300">&nbsp;</td>';         
                        if(sizeof($attValConfig)) {
                            foreach($attValConfig as $attValConfigSingle) {
							$name = $attValConfigSingle["attribute_id"].$_product->getId();							
							$xml .= '<input type="hidden" name="super_attribute['.$attValConfigSingle["attribute_id"].']" id="attribute'.$name.'"  />';
							    
                                foreach($attValConfigSingle['values'] as $attValConfigSingleVal) {	
										  $attribute_id=$attValConfigSingle["attribute_id"];
										  $collection = Mage::getModel('catalog/product')->getCollection();												
										  $collection->addAttributeToFilter('status', 1);
										  $collection->addFieldToFilter(array(
													array('attribute'=>$attValConfigSingle['attribute_code'],'eq'=>$attValConfigSingleVal['value_index']),
													));
										  foreach ($collection as $product_my) {
												$pro_id=$product_my->getId();
												if(in_array($pro_id,$main_child_id)) 
												{ $flg= 1; break; }
												else
												{ $flg= 0;} 
										  }		
										 						  
								          if($hasAtts==0)
										  	{

										  		$_SESSION['prev_att_id']=$attribute_id;
												$_SESSION['attr_code']=$attValConfigSingle['attribute_code'];
										  		$att_arry_first_loop[]=$attValConfigSingleVal['value_index'];			    
												$xml .= '<td width="200">';																					
												$xml .= $attValConfigSingleVal['label'];
												if(sizeof($attValConfig)==1) :
												$xml .= '<input id="qty" class="input-text qty" value="" maxlength="12" name="qty" type="text" onchange="test('.$_product->getId().','.$attValConfigSingle["attribute_id"].','.$attValConfigSingleVal['value_index'].',0,0,0,'.$c.');"';
												if($flg==0) { 
												$xml .='disabled="disabled" style="background-color:#CCCCCC;display:block; clear:both; margin-bottom:20px; " ';
												}
												$xml .= ' style="display:block; clear:both; margin-bottom:20px;" />';
												endif;
												$xml .= '</td>';
												$hasAttsIn++;
												echo $c++;
											}
										  elseif($hasAtts>0)
											{ 									
												$f_ar=array_unique($att_arry_first_loop);
												//var_dump($f_ar);
												$xml .= '</tr><tr><td width="200">';									
												$xml .= $attValConfigSingleVal['label'];
												$xml .= '</td>';
												
												for($i=0; $i < count($f_ar) ;$i++){
													  $collection_else = Mage::getModel('catalog/product')->getCollection();												
													  $collection_else->addAttributeToFilter('status', 1);
													  $collection_else->addFieldToFilter(array(
																array('attribute'=>$_SESSION['attr_code'],'eq'=>$f_ar[$i]),
																));
													  $collection_else->addFieldToFilter(array(
																array('attribute'=>$attValConfigSingle['attribute_code'],'eq'=>$attValConfigSingleVal['value_index']),
																));	
													  foreach ($collection_else as $product_my_else) {
															if(in_array($pro_id_else,$main_child_id)) 
															{ $flg_else= 1; break; }
															else
															{ $flg_else= 0;} 
															//echo "<br>";
													  }
													$add_textbox =1;
													$xml .= '<td width="200">'.$c_str_val.'<input id="qty" class="input-text qty" value="" maxlength="12" name="qty" type="text" onchange="test('.$_product->getId().','.$attribute_id.','.$attValConfigSingleVal['value_index'].','.$f_ar[$i].','.$_SESSION['prev_att_id'].','.$add_textbox.','.$c.');"';
												if(count($collection_else)== 0) { 											    
													$xml .='disabled="disabled" style="background-color:#CCCCCC;display:block; clear:both; margin-bottom:20px; " />';
												}
												else 
												{
													$xml .= ' style="display:block; clear:both; margin-bottom:20px;" />';
												}
												$xml .= '</td>';
												echo $c++;
												}
												$xml .= '</tr>';
											}
										  else{}
                                }
								$hasAtts++;
                            }
                        }
						$xml .= '</tr></table>';
                    }
                    echo($xml);
                    ?>
                    <input name="product" value="<?php echo($_product->getId()); ?>" type="hidden">
                    <button type="submit"><span><?php echo $this->__('Add to Cart') ?></span></button>
                    <script type="text/javascript" language="javascript">
                    function test(str,str1,str2,str3,str4,str5,c)
                    {
						//alert('in here');
						//alert(c);
						
                        var val=str2;                  
						if(str5==1)
						{
							//alert('hello');
							var otherid= "attribute_"+str1+"_"+c;
							var othername= "super_attribute_"+str1+"_"+c;
							var otherid_color= "attribute_"+str4+"_"+c;
							var othername_color= "super_attribute_"+str4+"_"+c;
							var input = document.createElement("input");
							input.setAttribute("type", "text");
							input.setAttribute("id", otherid_color);
							input.setAttribute("name", othername_color);
							input.setAttribute("value", str3);
							document.getElementById(str).appendChild(input);
							var input = document.createElement("input");
							input.setAttribute("type", "text");
							input.setAttribute("id", otherid);
							input.setAttribute("name", othername);
							input.setAttribute("value", str2);
							document.getElementById(str).appendChild(input);
							var input = document.createElement("input");
							input.setAttribute("type", "text");
							input.setAttribute("id", "c_str");
							input.setAttribute("name", "c_str");
							input.setAttribute("value", c);
							document.getElementById(str).appendChild(input);
						}
						else
						{
						var c=c+1;
						var name= "attribute"+str1+str;
						//document.getElementById(name).value = str2;
                        //alert("productid : " +str+"attribute_id : "+str1+"value : "+str2  );
							var otherid= "attribute_"+str1+"_"+c;
							var othername= "super_attribute_"+str1+"_"+c;
							/*var otherid_color= "attribute_"+str4+"_"+c;
							var othername_color= "super_attribute_"+str4+"_"+c;
							var input = document.createElement("input");
							input.setAttribute("type", "text");
							input.setAttribute("id", otherid_color);
							input.setAttribute("name", othername_color);
							input.setAttribute("value", str3);
							document.getElementById(str).appendChild(input);*/
							var input = document.createElement("input");
							input.setAttribute("type", "text");
							input.setAttribute("id", otherid);
							input.setAttribute("name", othername);
							input.setAttribute("value", str2);
							document.getElementById(str).appendChild(input);
							var input = document.createElement("input");
							input.setAttribute("type", "text");
							input.setAttribute("id", "c_str");
							input.setAttribute("name", "c_str");
							input.setAttribute("value", c);
							document.getElementById(str).appendChild(input);
                        //document.getElementById(name).value = str2;
						}
                        return c;
                    }
                    </script>
                    </form> 
                        
                    <?php endif; ?>                    
        	</li>
<?php endforeach; ?>
<script type="text/javascript">
    //<![CDATA[
        var productAddToCartForm = new VarienForm('product_addtocart_form');
        productAddToCartForm.submit = function(button, url) {
        if (this.validator.validate()) {
            var form = this.form;
            var oldUrl = form.action;
            if (url) {
                form.action = url;
            }
            var e = null;
            var msgHtml;
            var productImg = jQuery('.main-thumbnail').html();
            var windowOver = jQuery('#addedoverlay');
            var windowBox = jQuery('#added');
            var titleForBox = jQuery('#productname').text();
            if (!url) {
                url = jQuery('#product_addtocart_form').attr('action');
            }
            url = url.replace("checkout/cart","ajax/index");
            var data = jQuery('#product_addtocart_form').serialize();
            data += '&isAjax;=1';
            windowOver.show();
            windowBox.show().css({
             backgroundImage: "url('<?php echo $this->getSkinUrl('images/loading.gif')?>')"
            });
            try {
                jQuery.ajax( {
                    url : url,
                    dataType : 'json',
                    type : 'post',
                    data : data,
                    error : function(data) {
                          windowBox.css({
                                 backgroundImage: 'none'
                        }).html('<?php echo $this->__('Error') ?>');                       
                        windowOver.one('click',function(){
                            hidewindow(windowBox,windowOver);                    
                        });           
                                         
                        jQuery('#hidewindow').click(function(){
                            hidewindow(windowBox,windowOver);                    
                        });    
                    },
                    success : function(data) {
                       
                        if(data.status == 'SUCCESS'){
                            if(jQuery('.block-cart')){
                                jQuery('.block-cart').replaceWith(data.sidebar);
                            }
                            if(jQuery('.header .block-cart-header')){
                                jQuery('.header .block-cart-header').replaceWith(data.topcart);
                            }     
                            msgHtml = '<div class="image-popup">' + productImg + '</div><em>' + titleForBox + '</em> <?php echo $this->__('is toegevoegd aan de winkelwagen.') ?><div style="clear:both;"></div><button class="button" id="hidewindow"><span><span><?php echo $this->__('Verder winkelen') ?></span></span></button>&nbsp;<button class="button" onclick="[removed]=\'<?php echo $this->getUrl('checkout/cart')?>;\'"><span><span><?php echo $this->__('Bekijk winkelwagen') ?></span></span></button>';             
                        }else{
                            msgHtml = '<p class="error-msg" style="margin-bottom:15px;">' + data.message + '</p><button class="button" id="hidewindow"><span><span><?php echo $this->__('Verder winkelen') ?></span></span></button>&nbsp;<button class="button" onclick="[removed]=\'<?php echo $this->getUrl('checkout/cart')?>;\'"><span><span><?php echo $this->__('Bekijk winkelwagen') ?></span></span></button>';
                        }                       
                       
                          windowBox.css({
                                 backgroundImage: 'none'
                        }).html(msgHtml);                       
                        windowOver.one('click',function(){
                            hidewindow(windowBox,windowOver);                    
                        });           
                                         
                        jQuery('#hidewindow').click(function(){
                            hidewindow(windowBox,windowOver);                    
                        });          
                        
         

                    }
                });
            } catch (e) {
            }
            this.form.action = oldUrl;
            if (e) {
                throw e;
            }
        }
    }.bind(productAddToCartForm);
    productAddToCartForm.submitLight = function(button, url){
            if(this.validator) {
                var nv = Validation.methods;
                delete Validation.methods['required-entry'];
                delete Validation.methods['validate-one-required'];
                delete Validation.methods['validate-one-required-by-name'];
                if (this.validator.validate()) {
                    if (url) {
                        this.form.action = url;
                    }
                    this.form.submit();
                }
                Object.extend(Validation.methods, nv);
            }
        }.bind(productAddToCartForm);
        
        function hidewindow(windowBox,windowOver){
            windowOver.fadeOut(400);
            windowBox.fadeOut(400).html('');    
        }

    //]]>
    </script>
<?php echo "custom code ends here;"?>
<div class="category-products">
    <?php echo $this->getToolbarHtml() ?>
    <?php // List mode ?>
    <?php if($this->getMode()!='grid'): ?>
    <?php $_iterator = 0; ?>
    <ol class="products-list" id="products-list">
    <?php foreach ($_productCollection as $_product): ?>
        <li class="item<?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
            <?php // Product Image ?>
            <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(135); ?>" width="135" height="135" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" /></a>
            <?php // Product description ?>
            <div class="product-shop">
                <div class="f-fix">
                    <?php $_productNameStripped = $this->stripTags($_product->getName(), null, true); ?>
                    <h2 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $_productNameStripped; ?>"><?php echo $_helper->productAttribute($_product, $_product->getName() , 'name'); ?></a></h2>
                    <?php if($_product->getRatingSummary()): ?>
                    <?php echo $this->getReviewsSummaryHtml($_product) ?>
                    <?php endif; ?>
                    <?php echo $this->getPriceHtml($_product, true) ?>
                    <?php if($_product->isSaleable()): ?>
                        <p><button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button></p>
                    <?php else: ?>
                        <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
                    <?php endif; ?>
                    <div class="desc std">
                        <?php echo $_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description') ?>
                        <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $_productNameStripped ?>" class="link-learn"><?php echo $this->__('Learn More') ?></a>
                    </div>
                    <ul class="add-to-links">
                        <?php if ($this->helper('wishlist')->isAllow()) : ?>
                            <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
                        <?php endif; ?>
                        <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                            <li><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>" class="link-compare"><?php echo $this->__('Add to Compare') ?></a></li>
                        <?php endif; ?>
                    </ul>
                </div>
            </div>
        </li>
    <?php endforeach; ?>
    </ol>
    <script type="text/javascript">decorateList('products-list', 'none-recursive')</script>

    <?php else: ?>

    <?php // Grid Mode ?>

    <?php $_collectionSize = $_productCollection->count() ?>
    <?php $_columnCount = $this->getColumnCount(); ?>
    <?php $i=0; foreach ($_productCollection as $_product): ?>
        <?php if ($i++%$_columnCount==0): ?>
        <ul class="products-grid">
        <?php endif ?>
            <li class="item<?php if(($i-1)%$_columnCount==0): ?> first<?php elseif($i%$_columnCount==0): ?> last<?php endif; ?>">
                <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(135); ?>" width="135" height="135" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" /></a>
                <h2 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></a></h2>
                <?php if($_product->getRatingSummary()): ?>
                <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
                <?php endif; ?>
                
<?php $displayprice = Mage::getStoreConfig('customconfig/custom_group/custom_displayprice');/*name of section, name of group, name of option*/ ?>
<?php if($displayprice == 0): ?>
<?php // echo $this->getPriceHtml($_product, true) ?>
<?php else: ?>   
<?php echo $this->getPriceHtml($_product, true) ?>       
 <?php endif; ?>

				<div class="actions">
                    <?php if($_product->isSaleable()): ?>
                        <button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
                    <?php else: ?>
                        <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
                    <?php endif; ?>
                    <ul class="add-to-links">
                        <?php if ($this->helper('wishlist')->isAllow()) : ?>
                            <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
                        <?php endif; ?>
                        <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                            <li><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>" class="link-compare"><?php echo $this->__('Add to Compare') ?></a></li>
                        <?php endif; ?>
                    </ul>
                </div>
            </li>
        <?php if ($i%$_columnCount==0 || $i==$_collectionSize): ?>
        </ul>
        <?php endif ?>
        <?php endforeach ?>
        <script type="text/javascript">decorateGeneric($$('ul.products-grid'), ['odd','even','first','last'])</script>
    <?php endif; ?>

    <div class="toolbar-bottom">
        <?php echo $this->getToolbarHtml() ?>
    </div>
</div>
<?php endif; ?>
